简体   繁体   English

如何使用python re查找两个字符之间的信息(不包括空格)?

[英]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'

RegEx Demo 正则演示

\\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.

相关问题 在python中使用正则表达式消除单词之间的空格 - eliminate white spaces between words using regex in python 如何使用 python 在 dataframe 中查找带空格的行? - how to find rows with white spaces in a dataframe, using python? 删除特殊字符和单词python之间的空格 - remove white spaces between special characters and words python 如何使用python查找两个日期之间的日期(开始日期和结束日期除外) - How to find dates between two dates excluding start and end date using python 用两组词来查找和替换RE - Using Two Sets of Words for a Find and Replace RE Python re.findall在两个字符串之间,同时排除字符串 - Python re.findall between two strings while excluding strings Python检查是否存在行(两个关键字)而忽略了之间的空白 - Python check if line (two keywords) exists ignoring white spaces between 如何使用正则表达式查找两个字符之间有空格的字符串? - How to find string with spaces between two characters using Regex? 如何在Python的多行字符串中查找包含两部分(空格数未知)的子字符串的索引 - How to find the index of a substring having two parts (with unknown number of white spaces) in a multi line string in Python 如何使用正则表达式替换单词之间的空格? - How to replace spaces between words using regex?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM