[英]How to find information between two words excluding white spaces using python re?
Hi I am trying to develop a script using python that detects if there is something between two words. 嗨,我正在尝试使用python开发一个脚本,该脚本检测两个单词之间是否存在某些内容。 I am using regular expression
r'Madrid:(.*?)Newyork'
for this: 我
r'Madrid:(.*?)Newyork'
使用正则表达式r'Madrid:(.*?)Newyork'
:
import re
string_1 = "Madrid: good bars Newyork: good building Warranty: No"
pattern = r'Madrid:(.*?)Newyork'
searchObj = re.search(pattern, string_1, re.I)
if searchObj:
return True
else:
return False
This is working fine the problem is that it also detects whitespaces, and when I have whitespaces it should not find anything. 这个工作正常,问题在于它还可以检测到空格,当我有空格时,它什么也找不到。 I would like to develop an expression that excludes a whitespace from the match.
我想开发一个表达式,该表达式从比赛中排除空格。 For example, for these two is match is true and should be false:
例如,对于这两个,match是true,应该为false:
string_2 = "Madrid: Newyork: good building Warranty: No"
string_3 = "Madrid: Newyork: good building Warranty: No"
I am trying with [^\\s]
but Is not working, any help? 我正在尝试
[^\\s]
但没有任何帮助吗?
You can use this regex: 您可以使用此正则表达式:
reg = r'Madrid:(.*?\S.*?)Newyork'
\\S
in the middle ensures you are not matching all whitespaces between start and end strings. 中间的
\\S
确保您不匹配开始和结束字符串之间的所有空格。
无需使用其他正则表达式,您可以删除所有空格:
searchObj = re.search(pattern, string_1.replace(" ", ""), re.I)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.