Steve Steve - 5 months ago 13
Java Question

Understanding how Java's replaceFirst works with regular expressions

I have a String,

<parameter name="Browser" value="chrome" />
. I'd like to replace
chrome
with
Firefox
. My relevant Java code:

l = l.replaceFirst("value=\"*\"", "value=\"" + browser + '"');


Is turning the original String into

<parameter name="Browser" value="Firefox"chrome" />
. I'm confused how
chrome"
is not getting removed since the regex in
replaceFirst
matches the opening and closing parentheses.

Answer

In the first regex, value=\"*\", the \"*\" is matching 0 or more " characters, not any number of characters as you intended. The correct syntax for this would be value=\".*\".

You can test out a regex on http://regexr.com/ to get an idea of how your regex will work, with syntax highlighting.

Comments