亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果字符串有 X 個以@#$ 開頭的單詞,則 Python 正則表達式匹配:

如果字符串有 X 個以@#$ 開頭的單詞,則 Python 正則表達式匹配:

墨色風雨 2021-09-25 16:36:56
我想要做的是匹配字符串,如果該字符串包含 X 數量(比方說 5)以 @#$: 字符開頭的單詞。假設 X 為 5 的示例:@someword someotherword anotherword word1 word2 word3 => false@someword :someotherword #anotherword $word1 word2 word3 => false@someword :someotherword #anotherword $word1 #word2 $word3 => true
查看完整描述

3 回答

?
天涯盡頭無女友

TA貢獻1831條經驗 獲得超9個贊

假設這些符號僅在單詞字符之前使用,您可以使用此正則表達式:

(?:]\B[@#$:]\w+[^@#$:]*){5}

正則表達式演示

代碼:

>>> arr = ['@someword someotherword anotherword word1 word2 word3', 

'@someword :someotherword #anotherword $word1 word2 word3',

'@someword :someotherword #anotherword $word1 #word2 $word3']

>>> reg = re.compile(r'(?:\B[@#$:]\w+[^@#$:\n]*){5}');

>>> for i in arr:

...     print(reg.findall(i))

...

[]

[]

['@someword :someotherword #anotherword $word1 #word2 ']

  • \B:\b不匹配的地方。

  • [@#$:]\w+: 匹配 1+ 個以開頭的單詞字符 [@#$:]

  • [^@#$:]*: 匹配 0 個或多個不包含的字符 [@#$:]

  • (...){5}: 在當前輸入中匹配 5 個


查看完整回答
反對 回復 2021-09-25
?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

積極的前瞻將是做到這一點的一種方法:


input = "@someword :someotherword #anotherword $word1 #word2 $word3"

result = re.match(r'.*((?<=\s)|(?<=^))[@#$:]\S+.*(\s[@#$:]\S+.*){4}', input)


if result:

    print("Found a match")

這個問題很棘手,因為你想用 start a special symbol 匹配單詞[@#$:]。但是,我們不能只使用單詞邊界\b,因為特殊字符不是單詞字符。因此,相反,我們可以檢查目標術語開頭之前的內容是空格還是字符串的開頭。


查看完整回答
反對 回復 2021-09-25
?
慕雪6442864

TA貢獻1812條經驗 獲得超5個贊

正確的正則表達式是((?:[@#$].+){5}). 正則表達式解釋


例子:


import re

...

tst = """

    @someword someotherword anotherword word1 word2 word3

    @someword :someotherword #anotherword $word4 #word5 $word6

    @someword :someotherword #anotherword $word1 word2 word3

    @someword :someotherword #anotherword $word1 #word2 $word3

"""

res = re.findall(r"((?:[@#$].+){5})", tst)

print(res)

結果:


['@someword :someotherword #anotherword $word4 #word5 $word6', '@someword :someotherword #anotherword $word1 #word2 $word3']

分享


查看完整回答
反對 回復 2021-09-25
  • 3 回答
  • 0 關注
  • 298 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號