正则表达式查找某些模式之间的所有字符串

时间:2019-03-19 22:36:21

标签: python regex

我的输入字符串可以是以下几行之一:

Active App: Coffee (priority 34)

Active App: Hot Bread (priority 20)

Active App: Hot Baked Bread (priority 1)

etc...

在这种情况下,它可以是任何字符串[a-zA-Z](一个或多个单词),而不是“ Coffee”。

在“ (priority 34)”中,只有整数会更改。

那么如何从此行中获取“ Coffee” /“ Hot Bread” /“ Hot Baked Bread”?

我无法正确处理单词之间的空格。

1 个答案:

答案 0 :(得分:2)

这是使用python regex match()的简单解决方案:

它忽略了要捕获的应用程序名称之后的字符串部分。但这可以添加,如果重要的话。

它将捕获直到看到(,然后再从字符串中删除尾随空白字符。

import re;

myStr = "Active App: Hot Baked Bread (priority 34)";
appStr = re.match("Active App: ([^\(]*)", myStr);
print(appStr.group(1).rstrip());

这是一个仅捕获实际“ Active App”名称的版本,无需随后修剪字符串。并在打印之前检查是否找到了匹配项:

import re;

myStr = "Active App: Coffee Some (priority 34)";
appStringMatch = re.match("Active App: (.*)\s\(", myStr);
if appStringMatch:
    print(appStringMatch.group(1));