Pavan Manjunath
Pavan Manjunath

Reputation: 28525

Stop at first match using regex

This is an oft repeated question, but somehow I didn't find the previous answers exactly matching my requirement. There is a string

My name is Pavan. Am I a good boy?

I want to match only the first occurrence of the character a(irrespective of whether its at a word boundary or not ) in the above string. The simplest regex

a

will match all four as present in the string. All the other posts I searched on SO are suggesting using non-greedy match ?. But a+? doesn't solve the problem here as even the non-greedy match would be repeated 4 times.

So how shall I tell the regex engine to stop soon after the first match?

I might have asked a very trivial question, but bear with me as I've just started with regexes.

PS: I am using the following 2 engines to verify my results

GSkinner

RegexPal

I am not using any specific language and am just using the above tools to perform matches

Upvotes: 1

Views: 6268

Answers (2)

orlp
orlp

Reputation: 117661

In this particular case:

^[^a]*(a)

But most regex implementations have a function that returns only the first match.

Upvotes: 0

Joey
Joey

Reputation: 354396

You're confusing quantifiers in the regex language with the tools your language/framework gives you. Usually there is a method that returns all matches and one that returns only the first match (and one that just checks whether a regex matches).

In .NET Regex.Matches finds all matches, Regex.Match finds just the first one and you can use Regex.IsMatch to figure out whether a regex matches.

In Java you can use Matcher.find to find the first match or iterate to find all.

In Python there is re.search and re.findall.

Upvotes: 3

Related Questions