Search code examples
javaregexlookbehind

Why doesn't this positive lookbehind work?


I have this string (which is just the cut out part of a larger string):

00777: 50.000 bit/s

and want to capture the 50.000 bit/s part I've created a positive look-behind regex like this:

(?<=\d{5}: )\S+\s+\S+

Which works but when there are more spaces between the : and the number it doesn't - like expected.

So I did this:

(?<=\d{5}:\s+)\S+\s+\S+

But that doesn't work?! Why? Even this expression doesn't match any string:

(?<=\d{0,5}).*

What is it that I'm missing here?


Solution

  • This is because many regex engines don't support quantifiers(+,*,?) in lookbehind.

    Example:java,javascript

    EDIT

    Since you are using Java,you can use group

    Matcher m=Pattern.compile("\\d{5}:\\s+(\\S+\\s+\\S+)").matcher(input);
    if(m.find())
      value=m.group(1);