簡體   English   中英

正則表達式查找特定模式之間的所有字符串

[英]regex to find all the strings between certain patterns

我的輸入字符串可以是以下幾行之一:

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 ”?

我無法正確處理單詞之間的空格。

這是一個簡單的 python regex match()解決方案:

它會忽略您要捕獲的應用程序名稱之后的字符串部分。 但如果重要的話,可以添加。

它將捕獲直到它看到( ,然后從字符串中刪除尾隨的空白字符。

import re;

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

這是一個僅捕獲實際“活動應用程序”名稱的版本,之后無需修剪字符串。 並且還會在打印之前檢查是否找到匹配項:

import re;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM