Python 正则表达式:捕获字符不在空格内的情况
我试图编写一个Python 正则表达式:捕获字符不在空格内的情况,python,python-3.x,regex,Python,Python 3.x,Regex,我试图编写一个regex,以捕获特定的单个字符(在我的例子中是等号,'=')不在空格内的情况 示例: LABEL=SomeLabel # -> should be captured: spaces missing from both sides LABEL =SomeLabel # -> should be captured: space missing from the right LABEL= SomeLabel # -> should be captured
regex
,以捕获特定的单个字符(在我的例子中是等号,'='
)不在空格内的情况
示例:
LABEL=SomeLabel # -> should be captured: spaces missing from both sides
LABEL =SomeLabel # -> should be captured: space missing from the right
LABEL= SomeLabel # -> should be captured: space missing from the left
LABEL = SomeLabel # -> should **NOT** be captured: spaces in both sides
事实上,我在正则表达式方面相当差劲,所以分享我的尝试没有多大意义。
另外,我觉得这是一个相当复杂的任务…我会将零长度断言与此任务的备选方案结合起来,如下所示
import re
t1 = "LABEL=SomeLabel"
t2 = "LABEL =SomeLabel"
t3 = "LABEL= SomeLabel"
t4 = "LABEL = SomeLabel"
pattern = r"(?<=\S)=|=(?=\S)"
print(bool(re.search(pattern, t1)))
print(bool(re.search(pattern, t2)))
print(bool(re.search(pattern, t3)))
print(bool(re.search(pattern, t4)))
说明:
\S
表示非空白,我们查找前面有非空白((?我认为使用可选空格的交替选项可以\w+?=\w+\w+=\w+=\w+
您想要匹配的文本还是只需要找到匹配的文本?@AKSingh任何一种方式都可以。非常感谢您的回复。效果很好!只是一个注释..如果您认为我的示例是“真值表”,似乎使用and子句的解决方案比使用or子句的解决方案更合适。。
True
True
True
False