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

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

正則表達式匹配字符串及其周圍的 2 個字符

正則表達式匹配字符串及其周圍的 2 個字符

互換的青春 2023-08-03 16:23:04
我想匹配一個特定的單詞,然后檢索包含它的字符串及其兩側的兩個鄰居下面的代碼部分實現了這一點。但當匹配詞出現在字符串的開頭時,它會失敗。那么在正則表達式中是否有更高效、更靈活的方法來實現這一目標呢?text = "The world is a small place, we should try to take care of it"sub = r'(\w+|.)\W(\w+|.)\W+(try)\W+(\w+|.)\W'surrounding_text = re.findall(sub, text)
查看完整描述

4 回答

?
慕的地6264312

TA貢獻1817條經驗 獲得超6個贊

只需使用一個簡單的列表:


text = "The world is a small place, we should try to take care of it"

d = text.split()


try:

    idx = d.index('world')

    print("{} {} {}".format(d[idx - 1], d[idx], d[idx + 1]))

except ValueError:

    print("Not in the text.")

哪個產量


The world is

您需要在這里考慮負指數。


查看完整回答
反對 回復 2023-08-03
?
慕的地10843

TA貢獻1785條經驗 獲得超8個贊

您可以使用?量詞

要匹配單詞“try”和上一個或下一個單詞的一個字符:

試試看

(. )?try( .)?

解釋:

  • (. )?:匹配一個字符,然后匹配一個空格零次或一次

  • try: 字面意思是“嘗試”

  • ( .)?:匹配空格和一個字符零次或一次

如果您想匹配單詞字符或整個單詞,您可以修改.來匹配。試試看\w\w+

要匹配兩側最多兩個?單詞,您可以將 the 替換為{0, 2}?


查看完整回答
反對 回復 2023-08-03
?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

import re

text = "The world is a small place, we should try to take care of it"

sub = re.compile(r'(?P<all>(\w*)\s*try\s*(\w*))')


    rez = [m.groupdict() for m in sub.finditer(text)]

    for item in rez:

       print(item["all"])

    

    text = "try to take care of it"

    

    rez = [m.groupdict() for m in sub.finditer(text)]

    for item in rez:

       print(item["all"])

我測試了它:


The world is a small place, we should try to take care of it

try to take care of it

并得到:


should try to


try to

https://regex101.com/r/DlSJsJ/1


查看完整回答
反對 回復 2023-08-03
?
森欄

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

您可以將組設置為可選并使用錨點:

(?:^|(?:(\w+)\W+)?(\w+)\W+)(world)(?:\W+(\w+)|$)

正則表達式演示

  • (?:^|(?:(\w+)\W+)?(\w+)\W+):匹配行開始或之后的模式|

  • (?:(\w+)\W+)?(\w+)\W+:匹配一個或兩個單詞

  • (?:\W+(\w+)|$)匹配 1 個以上非單詞字符或字符串末尾之后的單詞


查看完整回答
反對 回復 2023-08-03
  • 4 回答
  • 0 關注
  • 187 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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