Regex用于查找数字、数字序列中的连字符和逗号



我正在尝试编写一个正则表达式,以允许数字、逗号和连字符在中间。我有两个图案(x表示数字(

  1. xx xx xx xxx xxx
  2. xx xx xx,xx xxx

我在第一种模式中尝试了这样的东西^[0-9](?:-?[0-9])*$

我无法破解第二个模式。我对Regex的理解不好,社区的一些帮助会很好。

有没有一种有效的方法可以在一个正则表达式中检查这两种模式。

谢谢Palani

使用

^d(?:[-,s]*d)*$

见证明。

解释

--------------------------------------------------------------------------------
^                        the beginning of the string
--------------------------------------------------------------------------------
d                       digits (0-9)
--------------------------------------------------------------------------------
(?:                      group, but do not capture (0 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
[-,s]*                  any character of: '-', ',', whitespace
(n, r, t, f, and " ") (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
d                       digits (0-9)
--------------------------------------------------------------------------------
)*                       end of grouping
--------------------------------------------------------------------------------
$                        before an optional n, and the end of the
string

Python:

import re
text = '12-34-56-789-0123'
if re.search(r'^d(?:[-,s]*d)*$', text):
print(f'"{text}" is valid')
else:
print(f'"{text}" is invalid')

结果:

"12-34-56-789-0123" is valid

你可以试试这个:

^[0-9](?:[-, ]{,2}[0-9])*$

或者这个:

^[0-9](?:[-, ]*[0-9])*$

如果您需要匹配EXACT的位数,此regex将执行以下操作:

(d{2}-){2}d{2}((-d{3}){2}|,sd{2}-d{3})

参见Regex101

根据您的问题,这应该可以解决您的问题:

^(?:[-, ]*d)*$

https://regex101.com/r/X7MQ7c/1

相关内容

最新更新