import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?: # Non capturing group 1\n"
+ " \\G # Matches where the regex engine stops in the previous step\n"
+ " (\\w+) # capture group 1: a regex word of 1+ chars\n"
+ " \\h* # zero or more horizontal spaces (space, tabs)\n"
+ " (?: # Non capturing group 2\n"
+ " =\\h* # literal '=' follower by zero or more hspaces\n"
+ " (\\w+) # capture group 2: a regex word of 1+ chars\n"
+ " )? # make the non capturing group 2 optional\n"
+ ")+ # repeat the non capturing group 1, one or more";
final String string = "Key name = value";
final String subst = "\\1\\2";
final Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html