Search code examples
regexsearchregex-lookaroundsregex-greedytext-search

Regular expression to find first match only


I have this text :-

SOME text, .....
Number of successes: 3556
Number of failures: 22
Some text, .....
Number of successes: 2623
Number of failure: 0

My requirement is to find the first occurrence of this pattern "Number of successes: (\d+)" which is Number of successes: 3556. But the above expression returns subsequent matches as well.

I want the regular expression to do this for me, unlike in java where i can use loop to iterate.

Can anyone help me with a regular expression that can find the first occurrence only.


Solution

  • One solution that should work in any language:

    (?s)\A(?:(?!Number of successes:).)*Number of successes: (\d+)
    

    Explanation:

    (?s)                      # Turn on singleline mode
    \A                        # Start of string
    (?:                       # Non-capturing group:
     (?!Number of successes:) # Unless this text intervenes:
     .                        # Match any character.
    )*                        # Repeat as needed.
    Number of successes:[ ]   # Then match this text
    (\d+)                     # and capture the following number
    

    See it live on regex101.com.