python2.7:使用regex匹配表达式

2024-03-28 20:09:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下几个条件:

asc_epsWarn_mu8                  # I want asc and epsWarn 
asc_ger_phiK_mi16                # I want asc and ger_Phik
ARSrt_FAC_RED5_DSR_AU16            # I want ARSrt and FAC_RED5_DSR    

基本上,我希望第一个_之前的字符在一个组中,第一个和最后一个下划线_之间的所有字符在第二个组中。你知道吗

我对regex不熟悉。是否可以为上述所有字符串编写一个正则表达式。我能想到的最好办法就是

(\w+)_(\w+)_(\w+)

但它不起作用。什么是合适的正则表达式?你知道吗


Tags: and条件字符wantfacascgerdsr
3条回答

您可以将此正则表达式与2个捕获组一起使用:

^([^_]+)_(.+)_[^_]*$

RegEx Demo

正则表达式详细信息:

  • ^:开始
  • ([^_]+):捕获组#1以匹配1+非下划线字符
  • _:匹配一个-
  • (.+):捕获组#2以匹配任何字符的1+,直到下一个匹配为止
  • _:匹配一个-
  • [^_]*:匹配0个或更多非下划线字符
  • $:结束

尝试使用此模式:

([^_]+)_(.*)_.*

示例脚本:

input = "ARSrt_FAC_RED5_DSR_AU16"
matches = re.match(r'([^_]+)_(.*)_.*', input)
if matchObj:
    print "part1: ", matches.group(1)
    print "part2: ", matches.group(2)

part1:  ARSrt
part2:  FAC_RED5_DSR

下面是regex模式的简要说明:

([^_]+) match and capture the term before the first underscore
_       match a literal underscore
(.*)    then greedily match and consume everything up until the last undescore
_       match the last underscore
.*      consume the remainder of the string

wordcharacter\w也匹配下划线。你知道吗

如果要匹配不带下划线的单词字符,可以使用否定字符类并匹配不带下划线的非空白字符[^\W_]

对于第二个组,可以使用两个具有重复模式的捕获组:

^([^\W_]+)_((?:[^\W_]+_)*)[^\W_]+$
  • ^字符串开头
  • ([^\W_]+)_Match 1+乘以除第1组中的下划线以外的单词字符,Match underline
  • (捕捉组2
    • (?:[^\W_]+_)*重复0多次匹配单词char,除了下划线,然后是下划线
  • )关闭组2
  • [^\W_]+匹配除下划线以外的单词字符的1+倍
  • $字符串结尾

Regex demo

相关问题 更多 >