Search code examples
regexpcreregular-language

match a text that follows a special string


I have a problem with my regular expression, I am trying to extract a string/number/whatever after a special string.

I have this string:

TEST 3098

There is 6 spaces between TEST and its value, but I am not quite sure if it is alway 6 spaces. I am trying this regular expression (PCRE)

(?<=TEST\s\s\s\s\s\s).*?(?=\s)

The result should be 3098. With my regular expression, I get the right result, but it is not strong enough, if the number of spaces changes I won't be able to extract it. The lookbehind should be in a limited size. Any suggestions?


Solution

  • You may use

    TEST\s*\K\S+
    

    If the number of whitespaces should be set to some min/max number use a limiting quantifier, \s{2,} will match two or more, \s{1,10} will allow 1 to 10 whitespaces.

    Details

    • TEST - TEST
    • \s* - 0 or more whitespaces
    • \K - match reset operator that omits the text matched so far from the overall match memory buffer
    • \S+ - 1+ non-whitespaces

    See the regex demo