![](/img/trans.png)
[英]python regex match line containing numbers after string with digit at end
[英]regex to match or ignore a set of two digit numbers
我正在寻找python中的正则表达式以匹配19之前和24之后的所有内容。
文件名是test_case _ *。py ,其中星号是1或2位数字。 例如:test_case_1.py,test_case_27.py。
最初,我认为[1-19]之类的东西应该起作用,但结果却比我想的要难得多。
有没有人致力于解决此类情况?
PS:即使我们可以为数字x之前的所有数字找到一个正则表达式,并且为数字y之后的所有数字找到一个正则表达式,我也可以。
我不会使用正则表达式来验证数字本身,而只会使用正则表达式来提取数字,例如:
>>> import re
>>> name = 'test_case_42.py'
>>> num = int(re.match('test_case_(\d+).py', name).group(1))
>>> num
42
然后使用类似:
num < 19 or num > 24
确保num
有效。 这样做的原因是,适应正则表达式要比适应num < 19 or num > 24
之类的要难得多 。
请执行以下操作(匹配整个文件名):
^test_case_([3-9]?\d|1[0-8]|2[5-9])\.py$
说明:
^ # beginning of string anchor
test_case_ # match literal characters 'test_case_' (file prefix)
( # begin group
[3-9]?\d # match 0-9 or 30-99
| # OR
1[0-8] # match 10-18
| # OR
2[5-9] # match 25-29
) # end group
\.py # match literal characters '.py' (file suffix)
$ # end of string anchor
就像是
"(?<=_)(?!(19|20|21|22|23|24)\.)[0-9]+(?=\.)"
One or more digits `[0-9]+`
that aren't 19-24 `(?!19|20|21|22|23|24)` followed by a .
following a _ `(?<=_)` and preceding a . `(?=\.)`
或更紧凑
"(?<=_)(?!(19|2[0-4])\.)[0-9]+(?=\.)"
其中20-24范围已被压缩。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.