0

I have this (.*)([USB][\s])* as a part of a regex. When i'm trying to match it with ABHISHEK USB it matches but full value matches with the first part. Is there any way by which i can ignore USB part from (.*) and have it matched to ([USB][\s]).

Abhishek Agarwal
  • 846
  • 4
  • 13
  • 34
  • 3
    Please share some examples of what should match and what should not – dotvav Sep 14 '15 at 12:03
  • This seems to be a very specific case. What about [`(.*?)(\s*USB)*$`](https://regex101.com/r/sW0zU6/1)? Note that here, `USB` should be at the end of the string. Please add more specifications to the question if it does not meet your need. Also note that `[USB]` matches 1 character, either `U` or `S` or `B`. And please let know if you need to match `ABHISHEK` with the regex, too. – Wiktor Stribiżew Sep 14 '15 at 12:03

4 Answers4

1

The star (*) says repeat zero or more times. This is done greedily. Therefore, the problem is that .* will try to match everything, and since the second star can match zero characters, no backtracking is performed. Two solutions:

  1. If you are sure, the (\sUSB)* part will be present, use + instead of * to repeat one or more times:

    (.*)(\sUSB)+
    
  2. If that is not the case, use non-greedy repetition for the first star - .*?:

    (.*?)(\sUSB)*
    
ndnenkov
  • 35,425
  • 9
  • 72
  • 104
0

Try this regex:

(.*)(?=USB[\s]*)

https://regex101.com/r/bG8vB4/1

mayo
  • 3,845
  • 1
  • 32
  • 42
0

I guess you are looking for this :

(.*?)\s*USB\s*

Note that, I changed your [USB] into USB

since [USB] matches U or S or B not string USB

Also I change the .* into non-greedy one, with the ?.

Kent
  • 189,393
  • 32
  • 233
  • 301
0

You have a greedy quantifier in your regex. Check Java Tutorial Differences Among Greedy, Reluctant, and Possessive Quantifiers

public class Test {
      @org.junit.Test
      public void testRegx() {

        String s = "(.*?)(USB)(.*)";
        String value = "ABHISHEK USB \\t";
        Matcher m = Pattern.compile(s).matcher(value);
        if(m.matches()) {
          Assert.assertEquals("ABHISHEK ", m.group(1));
          Assert.assertEquals("USB", m.group(2));
          Assert.assertEquals(" \\t", m.group(3));
        } else {
          Assert.assertFalse(true);
        }

      }
}
slbb
  • 144
  • 1
  • 6