Saturday, 22 December 2007

String's methods with regular expressions

The next example is for method replaceFirst(String regex, String replacement) which should find first substring that matches given regular expression and change it with replacement.

What if you want to replace only the first substring that is equal to "[sometnig]" - this represents regular expression that will match every single character from the word 'something', and, so 
a.replaceFirst("[something]", "anything");
will return (bold substrings are match and replacement):
  • if a="this is a [something] test"
    then "anythinghis is a [something] test"
  • if a="[something]"
    then "[anythingomething]"

What we need here is static method Pattern.quote(String s) which will make regular expression that matches string s as is. Thus, call
a.replaceFirst(Pattern.quote("[something]"), "anything");
if a="this is a [something] test"
will return "this is a anything test".

BTW: This is just for replacing only the first substring matched. If you want to replace all substring that are matched, you should use String's method replace. Also, there is method replaceAll which, again, uses String parameter for regular expression pattern matching.

No comments:

Popular Posts