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
I am not using any specific language and am just using the above tools to perform matches
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.Matchesfinds all matches,Regex.Matchfinds just the first one and you can useRegex.IsMatchto figure out whether a regex matches.In Java you can use
Matcher.findto find the first match or iterate to find all.In Python there is
re.searchandre.findall.