正则表达式:匹配点之间的所有内容,但如果找到括号则排除整个单词
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])
见regex demo。 详情:
\b
- 单词边界
config\.
- config.
子串
([\w.]+)
- 第 1 组:一个或多个单词或 .
个字符
\b
- 单词边界
(?![(\w])
- 如果在当前位置右侧立即有一个单词或 (
个字符,则匹配失败的否定前瞻。
参见Python demo:
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")
输出:
config.hello.world => hello.world
config.hello => hello
config.hello => hello
config.hello.world => hello.world
我目前正在尝试寻找一种正则表达式模式,它允许我匹配 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])
见regex demo。 详情:
\b
- 单词边界config\.
-config.
子串([\w.]+)
- 第 1 组:一个或多个单词或.
个字符\b
- 单词边界(?![(\w])
- 如果在当前位置右侧立即有一个单词或(
个字符,则匹配失败的否定前瞻。
参见Python demo:
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")
输出:
config.hello.world => hello.world
config.hello => hello
config.hello => hello
config.hello.world => hello.world