匹配除特定字符串以外的所有内容

2024-04-25 23:38:36 发布

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

我正在使用Python2.7,对正则表达式有一个问题。我的弦应该是这样的。。。你知道吗

"SecurityGroup:Pub HDP SG" 
"SecurityGroup:Group-Name" 
"SecurityGroup:TestName"

我的正则表达式如下所示

[^S^e^c^r^i^t^y^G^r^o^u^p^:].*

上述似乎是工作,但我有感觉,这是不是很有效,而且如果字符串中有“组”字,这将失败以及。。。你知道吗

我要寻找的是输出应该在冒号(:)之后找到任何内容。我还想我可以用第二组作为我的对手。。。但问题是,如果名称中有空格,那么我将无法获得正确的名称。你知道吗

(SecurityGroup):(\w{1,})

Tags: 字符串name名称内容groupsg空格pub
3条回答

为什么不直接做呢

security_string.split(':')[1]

抓住冒号后面的第二部分?你知道吗

也许是这样:

([^:"]+[^\s](?="))

Regex live here.

您可以使用lookbehind

pattern = re.compile(r"(?<=SecurityGroup:)(.*)")
matches = re.findall(pattern, your_string)

分解:

  (?<=  # positive lookbehind. Matches things preceded by the following group
    SecurityGroup:  # pattern you want your matches preceded by
  )  # end positive lookbehind
  (  # start matching group
    .*  # any number of characters
  )  # end matching group

在字符串"something something SecurityGroup:stuff and stuff"上测试时,它返回matches = ['stuff and stuff']。你知道吗

编辑:

正如在评论中提到的,pattern = re.compile(r"SecurityGroup:(.*)")完成了同样的事情。在本例中,您将匹配字符串"SecurityGroup:",后跟任何内容,但只返回后面的内容。这可能比我最初使用lookback的示例更清楚。你知道吗

相关问题 更多 >