Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex: find one-digit number

Tags:

regex

I need to find the text of all the one-digit number.

My code:

$string = 'text 4 78 text 558 [email protected] 5 text 78998 text';
$pattern = '/ [\d]{1} /';

(result: 4 and 5)

Everything works perfectly, just wanted to ask it is correct to use spaces? Maybe there is some other way to distinguish one-digit number.

Thanks

like image 675
lolalola Avatar asked Feb 26 '13 20:02

lolalola


1 Answers

First of all, [\d]{1} is equivalent to \d.

As for your question, it would be better to use a zero width assertion like a lookbehind/lookahead or word boundary (\b). Otherwise you will not match consecutive single digits because the leading space of the second digit will be matched as the trailing space of the first digit (and overlapping matches won't be found).

Here is how I would write this:

(?<!\S)\d(?!\S)

This means "match a digit only if there is not a non-whitespace character before it, and there is not a non-whitespace character after it".

I used the double negative like (?!\S) instead of (?=\s) so that you will also match single digits that are at the beginning or end of the string.

I prefer this over \b\d\b for your example because it looks like you really only want to match when the digit is surrounded by spaces, and \b\d\b would match the 4 and the 5 in a string like 192.168.4.5

To allow punctuation at the end, you could use the following:

(?<!\S)\d(?![^\s.,?!])

Add any additional punctuation characters that you want to allow after the digit to the character class (inside of the square brackets, but make sure it is after the ^).

like image 64
Andrew Clark Avatar answered Oct 08 '22 15:10

Andrew Clark