简体   繁体   中英

Find multiple string matches using Java regex

I am trying to use regex to find a match for a string between Si and (P) or Si and (I) .

Below is what I wrote. Why isn't it working and how do I fix it?

String Channel = "Si0/4(I) Si0/6( Si0/8K  Si0/5(P)";

if (Channel.length() > 0) {
    String pattern1 = "Si";
    String pattern2 = "(P)";
    String pattern3 = "(I)";

    String P1 = Pattern.quote(pattern1) + "(.*?)[" + Pattern.quote(pattern2) + "|" + Pattern.quote(pattern3) + "]";

    Pattern p = Pattern.compile(P1);
    Matcher m = p.matcher(Channel);

    while(m.find()){
        if (m.group(1)!= null)
        {
            System.out.println(m.group(1));
        }
        else if (m.group(2)!= null)
        {   
            System.out.println(m.group(2));
        }
    }

}

Expected output

0/4
0/5

Actual output

0/4
0/6
0/8K  Si0/5

Use a lookbehind and lookahead in your regex. And also you need to add space inside the character class, so that it won't this 0/8K string .

(?<=Si)[^\\( ]*(?=\\((?:P|I)\\))

DEMO

String str="Si0/4(I) Si0/6( Si0/8K Si0/5(P)";
String regex="(?<=Si)[^\\( ]*(?=\\([PI]\\))";
Pattern pattern = Pattern.compile(regex);
Matcher matcher =pattern.matcher(str);
while(matcher.find()){
    System.out.println(matcher.group(0));
}

Output:

0/4
0/5

You need to group your regex.It is currently

Si(.*?)[(P)|(I)]

Whereas it should be

Si(.*?)\(I\)|Si(.*?)\(P\)

See demo.

http://regex101.com/r/oO8zI4/8

[] means "any of these character", so it evaluates every letter in the block as if they were separated with OR.

If the result you're searching is always: number/number You can use:

Si(\\d+\\/\\d+)(?:\\(P\\)|\\(I\\))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM