Overlay group migration
Please take a look at the following code:
public static void main(String[] args) { String s = "a < b > c > d"; String regex = "(\\w\\s*[<>]\\s*\\w)"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(s); int i = 0; while (m.find()) System.out.println(m.group(i++)); } The output of the specified program: a < b, c > d
But I really expect a < b, b > c, c > d .
Is there something wrong with my regex here?
Try it.
String s = "a < b > c > d"; String regex = "(?=(\\w{1}\\s{1}[<>]{1}\\s{1}\\w{1}))."; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(s); while(m.find()) { System.out.println(m.group(1)); } Updated (based on green solution) :
String s = " something.js > /some/path/to/x19-v1.0.js < y < z < a > b > c > d"; String regex = "(?=[\\s,;]+|(?<![\\w\\/\\-\\.])([\\w\\/\\-\\.]+\\s*[<>]\\s*[\\w\\/\\-\\.]+))"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(s); while (m.find()) { String d = m.group(1); if(d != null) { System.out.println(d); } } You are right in your thinking that b> c matches a regular expression because this is happening.
But when you call Matcher :: find (), it returns the next input substring that matches the regular expression and does not match previous find () matches. Since "b> c" begins with "b", which was part of the match "a> b" returned by the previous call, it will not be returned by the find () function.
Based on John’s decision and adding some boundary matches, this works finally.
String s = " something.js > /some/path/to/x19-v1.0.js < y < z < a > b > c > d"; String regex = "(?=[\\s,;]+([\\w\\/\\-\\.]+\\s*[<>]\\s*[\\w\\/\\-\\.]+)[\\s,;$]*)."; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(s); while(m.find()) { System.out.println(m.group(1)); }