I'm trying to search a specified range of numbers and I'm currently using regular expressions. The lines I'm searching contain numbers from 00 to 30, but I only want to find the lines containing 02 to 22.

I have tried a few different things, but none of them work.

this returns 00 to 29

findRange = re.search('[0-2][0-9]', line)

this just doesn't work

findRange = re.search('[02-22]', line)

I know I could do this, but I'm hoping there's a cleaner way.

findRange = re.search('(02|03|04...', line)


6 Years
Discussion Span
Last Post by pyTony

Could you post your entire code? I have an idea for how it could work, but I would need to implement it in your existing code.
My idea:

  • Read line from file and convert to int
  • If int is less than 2, discard, if it is 2 or above, add the original string to an array
  • Repeat this until you get to your maximum number

It's a little long winded but it may work.
I'll code it once you have posted your code (don't forget code tags!)
Thanks :)


SgtMe, thanks for your reply, but the example I'm using is very simplified compared to my code, and it really wouldn't be worth your time to try and weed through it. I don't think your method would work because the line has more than just integers in it. I could try the if statements testing if the value is within the range I want, but that will require a second regular expression to find only the 2-digit integer. At that point, it may just be easier to use a bunch of or statements. Below is what my actual code RE looks like.

findHS = re.search('3281-0(02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22)  LEFT', line)

You can also use Pythons power to make the re for search:

makethis='3281-0(02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22)  LEFT'
also = '3281-0('+'|'.join('%02i' % num for num in range(2,23))+')  LEFT'
print also
print makethis == also
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.