Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式中{}符号的OR条件_Python_Regex - Fatal编程技术网

Python 正则表达式中{}符号的OR条件

Python 正则表达式中{}符号的OR条件,python,regex,Python,Regex,我有一个正则表达式: ((?:4903|4905|4911|4936|6333|6759)[0-9]{12}|(?:4903|4905|4911|4936|6333|6759)[0-9]{14})) 您可以注意到,在(?:4903 | 4905 | 4911 | 4936 | 6333 | 6759)[0-9]中的4位数字之后,我需要12位数字或14位数字。一种等价于[0-9]{12 | 14}的条件 有办法做到这一点吗?如果需要更多的澄清,请告诉我。为什么不干脆'[0-9]{12}($|[0

我有一个正则表达式:

((?:4903|4905|4911|4936|6333|6759)[0-9]{12}|(?:4903|4905|4911|4936|6333|6759)[0-9]{14}))
您可以注意到,在
(?:4903 | 4905 | 4911 | 4936 | 6333 | 6759)[0-9]
中的4位数字之后,我需要12位数字或14位数字。一种等价于
[0-9]{12 | 14}
的条件


有办法做到这一点吗?如果需要更多的澄清,请告诉我。

为什么不干脆
'[0-9]{12}($|[0-9]{2}$)'


如果您希望匹配未在字符串结尾处终止的14位数字,则需要将
'$'
标记替换为其他标记,例如
'?'

为什么不将
'[0-9]{12}($[0-9]{2}$')


如果您希望匹配未以字符串结尾的14位数字,则需要将
“$”
标记替换为其他标记,例如
?“

我相信此帖子解决了您的问题:我相信此帖子解决了您的问题:谢谢。早该想到这一点。但是我无法通过替换
“$”
来匹配14位数字这是一个对我有效的正则表达式:`
r'\b((?:4903 | 4905 | 4911 | 4936 | 6333 | 6759)[0-9]{12}(?::\b |[0-9]{2}\b))
。接受这个是因为我从你那里得到了这个想法。多谢各位much@MohitMotwani
“$”
表示字符串的结尾;您可以使用其他内容来表示边界,例如
'
(空白)或
[^0-9]
(非数字字符)。无论如何,很高兴听到你解决了你的问题!非常感谢。早该想到这一点。但是我无法通过替换
“$”
来匹配14位数字这是一个对我有效的正则表达式:`
r'\b((?:4903 | 4905 | 4911 | 4936 | 6333 | 6759)[0-9]{12}(?::\b |[0-9]{2}\b))
。接受这个是因为我从你那里得到了这个想法。多谢各位much@MohitMotwani
“$”
表示字符串的结尾;您可以使用其他内容来表示边界,例如
'
(空白)或
[^0-9]
(非数字字符)。无论如何,很高兴听到你解决了你的问题!
>>> regex = re.compile('[0-9]{12}($|[0-9]{2}$)')
>>> for i in range(11, 15):
...     print(f'Match for string of length {i}: {re.match(regex, "0" * i) is not None}')
... 
Match for string of length 11: False
Match for string of length 12: True
Match for string of length 13: False
Match for string of length 14: True