Reputation: 704
I am looking for a regex in python to match everything before 19 and after 24.
File names are test_case_*.py, where the asterisk is a 1 or 2 digit number. eg: test_case_1.py, test_case_27.py.
Initially, I thought something like [1-19] should work,it turned out to be much harder than I thought.
Has any one worked on a solution for such cases?
PS:i am ok even if we can find a one regex for all numbers before a number x and one for all numbers after a number y.
Upvotes: 1
Views: 2084
Reputation: 208425
The following should do it (for matching the entire filename):
^test_case_([3-9]?\d|1[0-8]|2[5-9])\.py$
Explanation:
^ # 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
Upvotes: 2
Reputation: 129497
I wouldn't use a regex for validating the number itself, I would use one only for extracting the number, e.g.:
>>> import re
>>> name = 'test_case_42.py'
>>> num = int(re.match('test_case_(\d+).py', name).group(1))
>>> num
42
and then use something like:
num < 19 or num > 24
to ensure num
is valid. The reason for this is that it's much harder to adapt a regex that does this than it is to adapt something like num < 19 or num > 24
.
Upvotes: 3
Reputation: 111840
Something like
"(?<=_)(?!(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 . `(?=\.)`
Or more compactly
"(?<=_)(?!(19|2[0-4])\.)[0-9]+(?=\.)"
where the 20-24 range has been compacted.
Upvotes: 0