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

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

將文本匹配到多個組的正則表達式

將文本匹配到多個組的正則表達式

素胚勾勒不出你 2021-09-14 21:12:30
我正在嘗試設置一個正則表達式來匹配文本,并且我希望一個特定的字符串與文本其余部分的單獨組匹配(如果存在)。例如,如果我的字符串是this is a test,我想this is a匹配第一組并test匹配第二組。我正在使用 python 正則表達式庫。以下是我想要的結果的更多示例this is a test- 第 1 組:this is a,第 2 組:testone day at a time- 第 1 組:one day at a time,第 2 組:one day test is- 第 1 組:one day,第 2 組:testtesting, 1,2,3 - 不匹配this is not a drill- 第 1 組:this is not a drill,第 2 組:在這些情況下,我在第二組中匹配的特定字符串是 test。我不確定如何設置正則表達式以正確匹配這些特定情況。
查看完整描述

2 回答

?
不負相思意

TA貢獻1777條經驗 獲得超10個贊

您可以嘗試以下正則表達式:


^(this.*?)(test)?$

正則表達式的解釋:


NODE                     EXPLANATION

--------------------------------------------------------------------------------

  ^                        the beginning of the string

--------------------------------------------------------------------------------

  (                        group and capture to \1:

--------------------------------------------------------------------------------

    this                     'this'

--------------------------------------------------------------------------------

    .*?                      any character except \n (0 or more times

                             (matching the least amount possible))

--------------------------------------------------------------------------------

  )                        end of \1

--------------------------------------------------------------------------------

  (                        group and capture to \2 (optional

                           (matching the most amount possible)):

--------------------------------------------------------------------------------

    test                     'test'

--------------------------------------------------------------------------------

  )?                       end of \2 (NOTE: because you are using a

                           quantifier on this capture, only the LAST

                           repetition of the captured pattern will be

                           stored in \2)

--------------------------------------------------------------------------------

  $                        before an optional \n, and the end of the

                           string


查看完整回答
反對 回復 2021-09-14
?
慕的地6264312

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

你可以試試這位朋友

^(?:(?!test))(?:(.*)(?=\btest\b)(\btest\b)|(.*))

解釋

  • ^(?:(?!test)) - 負面展望。不要匹配任何以測試開頭的內容。

  • (.*) - 匹配除換行符以外的任何內容。

  • (?=\btest\b)- 積極的前瞻。test單詞邊界之間的匹配。

  • (\btest\b)- 捕獲組比賽test。

  • | - 交替與邏輯 OR 相同。

  • (.*) - 匹配除換行符以外的任何內容。


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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