[英]How to match all words with regex, except urls or similiar?
我正在嘗試匹配字符串中的所有單詞,除了帶有URL的標點符號的字符串。
我嘗試了許多變體,但是當它在第二個字符串中工作時,第一個出現錯誤。
s1 = "My dog is nice! My cat not. www.test.org ?"
s2 = "I am."
regex = r"\b\w+\W* \b"
m1 = re.findall(regex, s1)
m2 = re.findall(regex, s2)
m1的輸出是正確的:
['My ', 'dog ', 'is ', 'nice! ', 'My ', 'cat ', 'not. ']
m2的輸出不是我想要的:
['I ']
... 但我想要
['I ', 'am.']
您需要額外的檢查...:
regex = r"\b\w+\W* \b|\b\w+\W$"
...以匹配空間不跟隨點結尾的情況。
工作代碼 :
import re
s1 = "My dog is nice! My cat not. www.test.org ?"
s2 = "I am."
regex = r"\b\w+\W* \b|\b\w+\W$"
m1 = re.findall(regex, s1)
m2 = re.findall(regex, s2)
print(m1) # ['My ', 'dog ', 'is ', 'nice! ', 'My ', 'cat ', 'not. ']
print(m2) # ['I ', 'am.']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.