Match this regex in python (negative lookahead?)

Viewed 50

I just can't find the solution at the moment to this regex. It's super simple and I'm a super newbie, and I don't know how to do it. I have those strings:

 palsar_cprof_1_1_10_0.sdat #1
 palsar_0.99_10_1_0.sdat #2
 srtm_cprof_10_10_5_0.sdat #3
 srtm_10_10_5_0.sdat #4

And I only want to match 2 and 4 because after srtm or palsar there is an underscore and then a number (0.99 and 10) and no further characters (cprof). What I tried is something like this (in python):

re.search(^(.*_)(?![az]]), string)

What I think is a negative lookahead and should assure that it start with anything until a _ and then doesn't have a letter from a-z. But it's not working. Any suggestions?

1 Answers

You can use

^[^_]*_\d

See the regex demo. Details:

  • ^ - start of string
  • [^_]* - zero or more chars other than _
  • _ - an underscore
  • \d - a digit.
import re
l = ['palsar_cprof_1_1_10_0.sdat #1','palsar_0.99_10_1_0.sdat #2','srtm_cprof_10_10_5_0.sdat #3','srtm_10_10_5_0.sdat #4']
rx = re.compile(r'^[^_]*_\d')
l = list(filter(rx.search, l))
print(l)
# => ['palsar_0.99_10_1_0.sdat #2', 'srtm_10_10_5_0.sdat #4']

See the Python demo

Related