我有這些輸入:
s1 = 'I am using c programming'.
s2 = = 'I am usingc programming'.
我想檢查 s1 或 s2 是否包含確切的單詞c 。
在 s1 和 s2 上運行這個正則運算式,它不會給出任何輸出:
x=s1 #x=s2
if re.search(r'\bc\ \ \b', x):
print(x)
預期結果:在 s1 中檢測 c
uj5u.com熱心網友回復:
您可以使用此正則運算式,使用不同風格的單詞邊界:
\bc\ \ \B
正則運算式演示
正則運算式詳細資訊:
\b:非單詞和單詞字符之間的單詞邊界c\ \: 匹配c\B: 逆詞邊界匹配\b不匹配的地方
蟒蛇代碼:
>>> import re
>>> s1 = 'I am using c programming'
>>> s2 = 'I am usingc programming'
>>> rx = re.compile(r'\bc\ \ \B')
>>> print (rx.findall(s1))
['c ']
>>> print (rx.findall(s2))
[]
>>>
uj5u.com熱心網友回復:
您可以執行以下操作
import re
x = 'I am using c programming'
pattern = re.compile(" c\ \ ")
results = re.findall(pattern, x)
if results:
print(x)
如果c 不在字串中,則為results空。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/436454.html
上一篇:字串中最長的單詞
下一篇:處理特定長度的字串
