[英]matching pattern in python before it reaches a certain character
I have a scenario where I have two strings to check for a match but the matching should be happening until a specific character (in my case -
) is found.我有一个场景,我有两个字符串来检查匹配,但匹配应该发生,直到找到特定字符(在我的情况下为-
)。 here is what I am doing with a positive look forward approach but it doesn't seem to work这是我正在用积极的前瞻性方法做的事情,但它似乎不起作用
txt1 = "ap1-tempora1yu"
txt2 = "ap1-gt4"
if re.search(".+?(?=-)", txt1) == re.search(".+?(?=-)", txt2):
print("found")
else:
print("not found")
I have also tried this regex patterns but no luck /^(.*?)-/
and /.+?(?=-)/
any help woud be great我也尝试过这种正则表达式模式,但没有运气/^(.*?)-/
和/.+?(?=-)/
任何帮助都会很棒
As @oh_my_lawdy commented, you don't really need regex here.正如@oh_my_lawdy 评论的那样,您在这里并不需要正则表达式。 However, if you want to use it then the issue with your code is that re.search()
returns a match object .但是,如果您想使用它,那么您的代码的问题是re.search()
返回匹配 object 。 For such objects even the value of the expression对于这样的对象,甚至表达式的值
re.search(".+?(?=-)", txt1) == re.search(".+?(?=-)", txt1)
(with the same string txt1
on both sides) is False
. (两边都有相同的字符串txt1
)是False
。 What you should compare instead are the actual substrings matching the pattern.您应该比较的是与模式匹配的实际子字符串。 These can be obtained using这些可以使用
re.search(".+?(?=-)", txt1).group(0)
More precisely this returns the first match group, but this is the only group in this case.更准确地说,这将返回第一个匹配组,但在这种情况下这是唯一的组。 In effect your code should be modified as follows:实际上,您的代码应修改如下:
txt1 = "ap1-tempora1yu"
txt2 = "ap1-gt4"
if re.search(".+?(?=-)", txt1).group(0) == re.search(".+?(?=-)", txt2).group(0):
print("found")
else:
print("not found")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.