1

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

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

(?:P|I) = [IP] ;-)
0

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

3 Comments

You ought to escape the parentheses: Si(.*?)\([IP]\)
@Tomalak it was der in the regex link.forgot here.thanx
Still not correct, because you have two groups in your expression but actually you only want one.
-1

[] 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\))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.