Joh*_*Zaj 1 regex regex-negation
我试图弄清楚如何找到不是年份的数字(我将一年定义为一个四位数的数字.)
例如,我想接
1
12
123
Run Code Online (Sandbox Code Playgroud)
但不是
1234为了避免日期(4位数).
如果正则表达式也接受了12345这很好,但不是解决这个问题所必需的
(注意:这些要求可能看起来很奇怪.它们是我遇到的更大解决方案的一部分)
如果可以使用lookbehind和lookahead,则以下内容应该有效:
(?<!\d)(\d{1,3}|\d{5,})(?!\d)
Run Code Online (Sandbox Code Playgroud)
说明:
(?<!\d) # Previous character is not a digit
(\d{1,3}|\d{5,}) # Between 1 and 3, or 5 or more digits, place in group 1
(?!\d) # Next character is not a digit
Run Code Online (Sandbox Code Playgroud)
如果您不能使用lookarounds,以下应该工作:
\b(\d{1,3}|\d{5,})\b
Run Code Online (Sandbox Code Playgroud)
说明:
\b # Word boundary
(\d{1,3}|\d{5,}) # Between 1 and 3, or 5 or more digits, place in group 1
\b # Word boundary
Run Code Online (Sandbox Code Playgroud)
Python示例:
>>> regex = re.compile(r'(?<!\d)(\d{1,3}|\d{5,})(?!\d)')
>>> regex.findall('1 22 333 4444 55555 1234 56789')
['1', '22', '333', '55555', '56789']
Run Code Online (Sandbox Code Playgroud)