Python中的正则表达式不匹配
我使用上面的正则表达式代码进行模式匹配。我的字符串如下Python中的正则表达式不匹配,python,regex,python-2.7,Python,Regex,Python 2.7,我使用上面的正则表达式代码进行模式匹配。我的字符串如下 with open(file_path, 'r') as logs: for line in logs.readlines(): reg = re.compile('publishing service \/rest\/service\/\w+-\w+-\w+-\w+-\w+\state\s\w+\b.*'); print(reg.search(line.strip())); 但我的代码无法匹配此字
with open(file_path, 'r') as logs:
for line in logs.readlines():
reg = re.compile('publishing service \/rest\/service\/\w+-\w+-\w+-\w+-\w+\state\s\w+\b.*');
print(reg.search(line.strip()));
但我的代码无法匹配此字符串。有什么建议吗 您错过了s并使用r:
更新您的正则表达式:
reg = re.compile(r'publishing service/rest/service\s*/\w+-\w+-\w+-\w+-\w+\sstate\b');
# here __^ here __^
请注意,模式中的\b是一个退格字符。在正则表达式字符串文本之前添加r前缀。此外,字符串中的/rest/service后面有一个空格,模式中没有空格。您应该使用\sstate、\state匹配空格和tate。实际要求是什么?请注意,结尾的\s\w+假定状态后有文本,但没有文本。请尝试r'publishing service/rest/service\s*/\w+?:-\w+{4}\sstate\b'。看,使用r对我来说很有效。谢谢:你还应该提到r@ThomasAyoub无论如何,这并不能解决问题。这个正则表达式。
reg = re.compile(r'publishing service/rest/service\s*/\w+-\w+-\w+-\w+-\w+\sstate\b');
# here __^ here __^
reg = re.compile('publishing service /rest/service /\w+-\w+-\w+-\w+-\w+-* state')