Regular expression to find first match only

Jaspreet Singh picture Jaspreet Singh · Nov 18, 2013 · Viewed 10.1k times · Source

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.

Answer

Tim Pietzcker picture Tim Pietzcker · Nov 18, 2013

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.