简体   繁体   English

在 python 中匹配这个正则表达式(负前瞻?)

[英]Match this regex in python (negative lookahead?)

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).我只想匹配 2 和 4,因为在 srtm 或 palsar 之后有一个下划线,然后是一个数字(0.99 和 10),没有其他字符(cprof)。 What I tried is something like this (in python):我尝试的是这样的(在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 az.我认为这是一个负面的前瞻,应该确保它以任何东西开始,直到 _ ,然后没有来自 az 的字母。 But it's not working.但它不起作用。 Any suggestions?有什么建议?

You can use您可以使用

^[^_]*_\d

See the regex demo .请参阅正则表达式演示 Details:细节:

  • ^ - start of string ^ - 字符串的开始
  • [^_]* - zero or more chars other than _ [^_]* - 除_以外的零个或多个字符
  • _ - an underscore _ - 下划线
  • \\d - a digit. \\d - 一个数字。
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查看Python 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM