![](/img/trans.png)
[英]regex catastrophic backtracking ; extracting words starts with capital before the specific word
[英]A regex pattern that matches all words starting from a word with an s and stopping before a word that starts with an s
我正在嘗試捕獲字符串中的單詞,以便第一個單詞以 s 開頭,如果下一個單詞也以 s 開頭,正則表達式將停止匹配。
例如。 我有字符串“Stack、Code 和 StackOverflow”。 我只想捕獲“堆棧、代碼和”,而不是在匹配中包含“StackOverflow”。
這就是我的想法:
我試過的正則表達式:
(?<=\s)S[a-z -,]*(?!(\sS))
我不知道如何讓它工作。
我認為這應該有效。 我從這個線程改編了正則表達式。 您也可以在這里進行測試。 我還包括了一個非正則表達式的解決方案。 我基本上跟蹤第一次出現的以“s”開頭的單詞和下一個以“s”開頭的單詞,並獲取該范圍內的單詞。
import re
teststring = " Stack, Code and StackOverflow"
extractText = re.search(r"(\s)[sS][^*\s]*[^sS]*", teststring)
print(extractText[0])
#non-regex solution
listwords = teststring.split(' ')
# non regex solution
start = 0
end = 0
for i,word in enumerate(listwords):
if word.startswith('s') or word.startswith('S'):
if start == 0:
start = i
else:
end = i
break
newstring = " " + " ".join([word for word in listwords[start:end]])
print(newstring)
Stack, Code and
Stack, Code and
您可以使用例如捕獲組:
(S(?<!\S.).*?)\s*S(?<!\S.)
解釋
(
捕獲組 1
S(?<.\S.)
匹配S
並斷言S
的左側沒有空白邊界.*?
匹配任意字符,盡可能少)
關閉組\s*
匹配可選的空白字符S(?<.\S.)
匹配S
並斷言S
的左側沒有空白邊界示例代碼:
import re
pattern = r"(S(?<!\S.).*?)\s*S(?<!\S.)"
s = "Stack, Code and StackOverflow"
m = re.search(pattern, s)
if m:
print(m.group(1))
Output
Stack, Code and
另一種選擇使用環視將S
斷言到右側而不使用它以允許多個匹配項相互匹配:
S(?<!\S.).*?(?=\s*S(?<!\S.))
import re
pattern = r"S(?<!\S.).*?(?=\s*S(?<!\S.))"
s = "Stack, Code and StackOverflow test Stack"
print(re.findall(pattern, s))
Output
['Stack, Code and', 'StackOverflow test']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.