replaceAll and beginning of line (java)

I would like to use String’s replaceAll function to delete any char that is not in a given set. I tried

x = x.replaceAll("^[A-Za-z]", "");

However this is not working because when placed at the beginning of the expression, the ^ character has another meaning (match the beginning of a line).

How can I get the behavior I want? I could not find any help on the correct syntax.



Are you looking for the negation of the range? Then it has to be inside the brackets.

x = x.replaceAll("[^A-Za-z]", "");

More in the Java Doc.

Leave a Reply

Your email address will not be published. Required fields are marked *