I am writing some Regex codes. How can I only search for the first instance
that the string appears in the text. For example, if I want to search for the first
number that appears in a text(I don’t care about other numbers and I don’t want
them highlighted), how do I specify that in Regex?
I am writing raw Regex code and testing them on online testers such as
Rubular.com and regexpal.com .
That is how regex works by default, you usually have to provide a global option or use a specific function to find all matches.
So, if you were to use the regex
\d+to look for one or more digits, the regex engine would only match up to the first group of digits (first number).Note that this may not be the case if you are using an online tool or text editor instead of a programming language, so if this doesn’t help please specify how you are performing your regex search.
You could use the following regex to get the first number in the first capture group and not match anything else:
Explanation: