Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

regex: find one-digit number

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 (). 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 d for your example because it looks like you really only want to match when the digit is surrounded by spaces, and d 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 ^).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...