[英]Regex to match n digits ignoring spaces and symbols
我很难找到有关正则表达式的一些信息,但我仍在苦苦挣扎。
假设我们有这个:
0123 4567 8910
该示例有空格,但它们可以是-
或,
或+
或不是数字的东西。
我试图获得 10 个数字(或 5 或 11 个),单独检测,忽略与数字不同的所有其他字符。
使用这个: [0-9] 匹配任何数字,我知道。 如果我做这样的事情 [0-9]{10} 永远不会检查任何东西,因为这种模式正在寻找所有 10 位数字在一起,我需要正则表达式来一一计算这 10 位,无论是否与数字不同在字符串中...
我正在使用这个正则表达式: [0-9](?=(?:[^0-9]*[0-9]){4,16}(?![^0-9]*[0-9]))
问题是这会检测除最后 4 位数字之外的所有内容,而不是我需要的特定 10 位数字……对此的任何建议将不胜感激……
编辑
我能够做到这一点......换句话说,我的意思是,我能够留下 10 个未标记的字符......我需要按照这个正则表达式的工作方式来做相反的事情:
[0-9](?=(?:[^0-9]*[0-9]){10,}(?![^0-9]*[0-9]))
这是示例。
这就是目标。 使用正则表达式,获得 5、10 或 12 个像这样的第一个字符(例如 12 个字符):
尝试这个:
/(\\d\\D*){10}/
(一组数字后跟零个或多个非数字重复 10 次)
仅获取数字:
let arr = '0123 4567 8910' .match(/(\\d\\D*){10}/)[0] .split(/\\D+|/) console.log(arr)
我假设你想匹配n 个初始数字(如果有更多,你想省略 superflouos 数字)。
为此,您需要一个两步走的方法:
要在 JavaScript 代码中表达它,请定义以下函数:
function mtch(str, cnt) {
return str.replace(/\D+/g, '').match(new RegExp('\\d{' + cnt + '}'));
}
然后当你调用它试图匹配现有的位数时:
var str = '0123 4567 8910';
res = mtch(str, 8);
你会得到01234567
。
但是,如果您尝试匹配不存在的位数,例如
res = mtch(str, 18);
你会得到null
。
您可以使用下面的正则表达式来确认:
", +-"
的四个字符;", +-"
中的两个字符不能连续出现; 和该字符串包含指定数量的数字(链接处为 10 位数字)。
^(?=\\d[\\d ,+-] \\d$)(?!. [ ,+-]{2})(?=(?:\\D*\\d){10}\\D*$)
对于与此正则表达式匹配的每个字符串,只需提取数字(可能通过将所有非数字转换为空字符串)。
正则表达式执行以下操作:
^ # match beginning of string
(?= # begin a positive lookahead
\d[\d ,+-]*\d # match 1 digit, 0+ chars in char class, 1 digit
$ # match end of line
) # end positive lookahead
(?! # begin negative lookahead
.* # match 0+ chars
[ ,+-]{2} # match 2 chars in the char class
) # end negative lookahead
(?= # begin a positive lookahead
(?:\D*\d) # match 0+ non-digits followed by 1 digit
{10} # execute non-capture group 10 times
\D* # match 0+ non-digits
$ # match end of line
) # end positive lookahead
获得相同结果的另一种方法,不使用正则表达式:
num_of_digits = 10
results = [int(x) for x in input_string if x.isdigit()][:num_of_digits]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.