Getting overlapping matches with multiple patterns in Java regex

前端 未结 3 416
甜味超标
甜味超标 2021-01-16 02:10

I have the same problem as in this link

but with multiple patterns. My regex is like:

Pattern word = Pattern.compile("([\\w]+ [\\d]+)|([\\d]+ suit         


        
相关标签:
3条回答
  • 2021-01-16 02:52

    You could try the below regex which uses positive lookahead assertion.

    (?=(\b\w+ Road \d+\b)|(\b\d+ suite\b))
    

    DEMO

    String s = "XYZ Road 123 Suite";
    Matcher m = Pattern.compile("(?i)(?=(\\b\\w+ Road \\d+\\b)|(\\b\\d+ suite))").matcher(s);
    while(m.find())
    {
        if(m.group(1) != null) System.out.println(m.group(1));
        if(m.group(2) != null) System.out.println(m.group(2));
    }
    

    Output:

    XYZ Road 123
    123 Suite
    
    0 讨论(0)
  • 2021-01-16 02:54
    (?=(\b[\w]+ [\d]+))|(?=(\b[\d]+ suite))|(?=(\b[\w]+ road))
    

    Try this.See demo.Grab the captures.

    https://regex101.com/r/dU7oN5/16

    Use positive lookahead to avoid string being consumed.

    0 讨论(0)
  • 2021-01-16 02:57

    Something like this, maybe?

    Pattern p = Pattern.compile("([\\w ] Road) (\\d+) (Suite)");
    Matcher m = p.matcher(input);
    if(m.find) {
       System.out.println(m.group(1) + " " + m.group(2));
       System.out.println(m.group(2) + " " + m.group(3));
    }
    
    0 讨论(0)
提交回复
热议问题