Jaspreet Singh
Jaspreet Singh

Reputation: 13

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.

Upvotes: 1

Views: 11070

Answers (3)

jkshah
jkshah

Reputation: 11703

Try using grep with -m option

grep -m 1 'Number of successes: [0-9]\+' file

Upvotes: 0

Olivier Dulac
Olivier Dulac

Reputation: 3791

Just in case the requirements to do it via regexp is not really a requirement, here are alternatives to the (nice) approach by Tim (who uses only regexp)

awk ' $0~/Number of successes: [1-9][0-9]*/ { print $0 ; exit 0 ;}'

or the really simple

grep 'Number of successes: [1-9][0-9]*' | head -1

I much prefer the awk one, as it quits as soon as it sees the first match, whereas the 2nd one could process many lines after it (until it receives the SIGPIPE or end of file)

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

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.

Upvotes: 7

Related Questions