正则表达式:查找一位数 [英] regex: find one-digit number

查看:80
本文介绍了正则表达式:查找一位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到所有一位数的文本.

我的代码:

$string = 'text 4 78 text 558 my.name@gmail.com 5 text 78998 text';$pattern = '/[\d]{1}/';

(结果:4 和 5)

一切正常,只是想问使用空格是否正确?也许还有其他方法可以区分一位数.

谢谢

解决方案

首先,[\d]{1}等价于\d.>

至于您的问题,最好使用零宽度断言,例如 lookbehind/lookahead 或字边界 (\b).否则你将不会匹配连续的单个数字,因为第二个数字的前导空格将被匹配为第一个数字的尾随空格(并且不会找到重叠匹配项).

我会这样写:

(?

这意味着仅当数字前面没有非空白字符且后面没有非空白字符时才匹配数字".

我使用了双否定像 (?!\S) 而不是 (?=\s) 这样你也可以匹配开头的单个数字或字符串的结尾.

我更喜欢这个而不是 \b\d\b 作为你的例子,因为看起来你真的只想在数字被空格包围时匹配,并且 \b\d\b 将匹配192.168.4.5

这样的字符串中的 45

要允许在末尾使用标点符号,您可以使用以下内容:

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

将您希望在数字后允许的任何其他标点字符添加到字符类(在方括号内,但确保它在 ^ 之后).

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

My code:

$string = 'text 4 78 text 558 my.name@gmail.com 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

解决方案

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 ^).

这篇关于正则表达式:查找一位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆