此问题在此处已有答案:
Reference - What does this regex mean?(1个答案)
3天前关闭。
用户可以输入如下字符串:
4409101800
16.10.10.110
4409101800 - Lorem Ipsum is simply dummy text of the printing and typesetting industry.
16.10.10.110 - Lorem Ipsum is simply dummy text of the printing and typesetting industry.
数字代码始终位于字符串的开头。
我只需要一个字符串包含前6位数字,包括点(如果有的话)。
就像这样:
440910
16.10.10
我试着创建一个正则表达式,但是失败了。我怎样才能找到一个优雅的解决方案来完成这个任务呢?
4条答案
按热度按时间rm5edbpk1#
捕获前5个数字,并在中间添加许多点(可选),然后匹配最后一个数字:
Regex101
kdfy810k2#
如果你可以简单地做一个简单的循环,检查每个字符是否是数字,你可以做如下的事情:
n9vozmp43#
您可以运行一个
for
循环来检查每个字符,然后返回包含前6位数字的字符串的slice()
。第二种基于正则表达式的解决方案的作用更为严格,因为如果在输入字符串中找不到所需的6位数字,它将返回一个空字符串。
hmae6n7t4#
您可以使用下列正则表达式:
它将匹配任何数字,最后匹配一个可能存在也可能不存在的点(
?
使它成为可选的)。只有当模式重复6次时,它才会匹配,并且结果被 Package 在一个组中。m
标志使它也能在多行上工作