views:

472

answers:

2

Just could not get this one and googling did not help much either..

First something that I know: Given a string and a regex, how to replace all the occurrences of strings that matches this regular expression by a replacement string ? Use the replaceAll() method in the String class.

Now something that I am unable to do. The regex I have in my code now is [^a-zA-Z] and I know for sure that this regex is definitely going to have a range. Only some more characters might be added to the list. What I need as output in the code below is Worksheet+blah but what I get using replaceAll() is Worksheet++++blah

String homeworkTitle = "Worksheet%#5_blah";
String unwantedCharactersRegex = "[^a-zA-Z]";
String replacementString = "+";
homeworkTitle = homeworkTitle.replaceAll(unwantedCharactersRegex,replacementString);
System.out.println(homeworkTitle);

What is the way to achieve the output that I wish for? Are there any Java methods that I am missing here?

+5  A: 
[^a-zA-Z]+

Will do it nicely.

You just need a greedy quantifier in order to match as many non-alphabetical characters you can, and replace the all match by one '+' (a - by default - greedy quantifier)

Note: [^a-zA-Z]+? would make the '+' quantifier lazy, and would have give you the same result than [^a-zA-Z], since it would only have matched only one non-alphabetical character at a time.

VonC
Just a quibble: You don't really need a "greedy" pattern as much as you need a <i>quantifier</i>--saying one or more occurrences--which are by default greedy.
Axeman
+2  A: 
String unwantedCharactersRegex = "[^a-zA-Z]"

This matches a single non-letter. So each single non-letter is replaced by a +. You need to say "one or more", so try

String unwantedCharactersRegex = "[^a-zA-Z]+"
Paul