c > d"; String reg...">

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?

+4
source share
3 answers

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); } } 
+2
source

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.

+3
source

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)); } 
+1
source

Source: https://habr.com/ru/post/1346167/


All Articles