Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex to match one and only one digit

Tags:

regex

I need to match a single digit, 1 through 9. For example, 3 should match but 34 should not.

I have tried:

\d
\d{1}
[1-9]
[1-9]{1}
[1-9]?

They all match 3 and 34. I am using regex for this because it is part of a much larger expression in which I am using alternation.

like image 231
BattlFrog Avatar asked Jan 04 '23 16:01

BattlFrog


1 Answers

The problem with all of your examples, of course, is that they match the digit, but don't keep themselves from matching multiple digits next to each other.

In the following example:

Some text with a 3 and a 34 and what about b5 and 64b?

This regex will match only the lone 3. It uses word boundaries, a handy feature.

\b[1-9]\b

It gets more complicated if you want to match single digits inside words, like the 5 in my example, but you didn't specify if you'd want that, so I'll leave that out for now.

like image 198
Tim S. Avatar answered Jan 11 '23 18:01

Tim S.