正则表达式匹配或忽略一组两位数字

时间:2013-08-05 19:44:27

标签: python regex

我正在寻找python中的正则表达式来匹配19之前和24之后的所有内容。

文件名是 test_case _ * .py ,其中星号是1位或2位数字。 例如:test_case_1.py,test_case_27.py。

最初,我认为像 [1-19] 这样的东西应该有效,但结果却比我想象的要难得多。

有没有人为此类案件制定解决方案?

PS:即使我们可以在数字x之前为所有数字找到一个正则表达式,在数字y之后为所有数字找到一个正则表达式,我也没问题。

3 个答案:

答案 0 :(得分:3)

我不会使用正则表达式来验证数字本身,我只会使用一个来提取数字,例如:

>>> 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这样的东西,正好适应这样做的正则表达式

答案 1 :(得分:2)

以下应该这样做(用于匹配整个文件名):

^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

答案 2 :(得分:1)

这样的东西
"(?<=_)(?!(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 . `(?=\.)`

http://regexr.com?35rbm

或更紧凑

"(?<=_)(?!(19|2[0-4])\.)[0-9]+(?=\.)"

20-24范围已被压缩。

相关问题