Так что я не думаю, что какой-либо из этих ответов оправдывает более абстрактные случаи следующего вопроса, с которым я столкнулся, поэтому я написал некоторый код, который работает в более общем случае:
/**
*
* @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);
}
На вашем примере это именно так, как вы описываете:
String regex = "foo(_+f)";
String line = "foo___f blah foo________f";
System.out.println(FileParsing.replace(regex, line, "baz"));
Распечатывается:
foobaz blah foobaz