簡體   English   中英

正則表達式:匹配點之間的所有內容,但如果找到括號則排除整個單詞

[英]Regex: Match everything between dots, but exclude entire word if parenthesis is found

我目前正在嘗試找到一個正則表達式模式,它允許我匹配過去config. , 但不匹配任何帶左括號的單詞。 例子:

  • config.hello.world應該匹配hello.world
  • config.hello應該匹配hello
  • config.hello.world(應該匹配hello
  • config.hello.world*10應該匹配hello.world

我一直無法弄清楚括號部分。 上面的第一個、第二個和第四個例子我已經開始工作了

\bconfig\.([\w\.]+)

任何幫助將不勝感激,謝謝。

您可以使用

\bconfig\.([\w.]+)\b(?![(\w])

請參閱正則表達式演示 詳情

  • \b - 單詞邊界
  • config\. - 一個config. substring
  • ([\w.]+) - 第 1 組:一個或多個單詞或. 字符
  • \b - 單詞邊界
  • (?![(\w]) - 如果在當前位置右側立即有一個單詞或(字符,則匹配失敗的否定前瞻。

請參閱Python 演示

import re
texts = ['config.hello.world','config.hello','config.hello','config.hello.world']
rx = re.compile(r'\bconfig\.([\w.]+)(?![(\w])')
for text in texts:
    m = rx.search(text)
    if m:
        print(text + " => " + m.group(1))
    else:
        print(text + " => NO MATCH")

Output:

config.hello.world => hello.world
config.hello => hello
config.hello => hello
config.hello.world => hello.world

暫無
暫無

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

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