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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With