簡體   English   中英

匹配除特定字符串外的所有內容

[英]Match everything except a specific string

我看過很多標題相似的帖子,但沒有發現任何適用於python或以下站點的內容: https : //regex101.com

除了特定文字,我該如何匹配所有內容?

我的文字:

1234_This is a text Word AB

Protocol  Address          ping
Internet  1.1.1.1            - 
Internet  1.1.1.2            25 
Internet  1.1.1.3            8 
Internet  1.1.1.4            - 

1234_This is a text Word BCD    
Protocol  Address          ping
Internet  2.2.2.1            10 
Internet  2.2.2.2            - 

我想匹配Word \\w+ ,然后匹配其余部分,直到下一個1234。因此結果應該是(返回標記為() ):

(1234_This is a text (Word AB))(

Protocol  Address          ping
Internet  1.1.1.1            - 
Internet  1.1.1.2            25 
Internet  1.1.1.3            8 
Internet  1.1.1.4            - 

)(1234_This is a text (Word BCD)(    
Protocol  Address          ping
Internet  2.2.2.1            10 
Internet  2.2.2.2            - )

第一部分很容易,因為: matches = re.findall(r'1234_This is a text (Word \\w+)', var)但是下一部分我無法實現。 我已經嘗試過否定的前瞻: ^(?!1234)但隨后它不再匹配...

查看正則表達式在這里使用

(1234[\w ]+(Word \w+))((?:(?!1234)[\s\S])*)

使用s修飾符可以使用以下內容。
查看正則表達式在這里使用

(1234[\w ]+(Word \w+))((?:(?!1234).)*)

說明

  • (1234[\\w ]+(Word \\w+))將以下內容捕獲到捕獲組1中
    • 1234從字面上匹配
    • [\\w ]+匹配一個或多個單詞字符或空格
    • (Word \\w+)將以下內容捕獲到捕獲組2中
      • Word逐字匹配(注意尾隨空格)
      • \\w+匹配任何單詞字符一次或多次
  • ((?:(?!1234)[\\s\\S])*)將以下內容捕獲到捕獲組2中
    • (?:(?!1234)[\\s\\S])*匹配以下任意次數( 回火貪婪令牌
      • (?!1234)負向前瞻,確保后面的內容不匹配
      • [\\s\\S])*任意次數匹配任何字符

如您所說:

我想匹配Word \\ w +,然后匹配其余部分,直到下一個1234。

你想要這樣的東西嗎?

import re
pattern=r'((1234_This is a text) (Word\s\w+))((\n?.*(?!\n\n))*)'
string="""1234_This is a text Word AB

Protocol  Address          ping
Internet  1.1.1.1            -
Internet  1.1.1.2            25
Internet  1.1.1.3            8
Internet  1.1.1.4            -

1234_This is a text Word BCD
Protocol  Address          ping
Internet  2.2.2.1            10
Internet  2.2.2.2            -"""

match=re.finditer(pattern,string,re.M)
for find in match:
    print("this is group_1 {}".format(find.group(1)))
    print("this is group_3 {}".format(find.group(3)))




    print("this is group_4 {}".format(find.group(4)))

輸出:

this is group_1 1234_This is a text Word AB
this is group_3 Word AB
this is group_4 

Protocol  Address          ping
Internet  1.1.1.1            -
Internet  1.1.1.2            25
Internet  1.1.1.3            8
Internet  1.1.1.4            
this is group_1 1234_This is a text Word BCD
this is group_3 Word BCD
this is group_4 
Protocol  Address          ping
Internet  2.2.2.1            10
Internet  2.2.2.2            -

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM