So I don't think any of these answers do justice to more abstract cases of the following question, which is something I ran into myself, so I wrote some code that works in the more general case:
/**
*
* @param regex Pattern to find in oldLine. Will replace contents in ( ... ) - group(1) - with newValue
* @param oldLine Previous String that needs replacing
* @param newValue Value that will replace the captured group(1) in regex
* @return
*/
public static String replace(String regex, String oldLine, String newValue)
{
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(oldLine);
if (m.find())
{
return m.replaceAll(replaceGroup(regex, newValue));
}
else
{
throw new RuntimeException("No match");
}
}
/**
* Replaces group(1) ( ... ) with replacement, and returns the resulting regex with replacement String
* @param regex Regular expression whose parenthetical group will be literally replaced by replacement
* @param replacement Replacement String
* @return
*/
public static String replaceGroup(String regex, String replacement)
{
return regex.replaceAll("\\(.*\\)", replacement);
}
On your example, it does precisely as you describe:
String regex = "foo(_+f)";
String line = "foo___f blah foo________f";
System.out.println(FileParsing.replace(regex, line, "baz"));
Prints out:
foobaz blah foobaz