[英]Python Regex: Optional White Space Around Matching Group
I would like to accept one white space before and after the operator group in the following regex. 我想在以下正则表达式中的运算符组之前和之后接受一个空格。 How would I accomplish this? 我将如何完成?
(?P<key>.*?)(?P<operator>NOT LIKE|LIKE|<=>|>=|<=|!=|<>|=|>|<)(?P<values>.*)
Three examples that I would like to match this regex would be: 我想匹配此正则表达式的三个示例是:
user LIKE bob%
user=bob
user = bob
text = 'user = bob'
a = re.match(r'(?P<key>.*?) ?(?P<operator>NOT LIKE|LIKE|<=>|>=|<=|!=|<>|=|>|<) ?(?P<values>.*)',text)
print a.group()
Output: 输出:
user = bob
if you want spaces to be part of your second group. 如果您希望空格成为第二组的一部分。 You could do below. 您可以在下面做。
a = re.match(r'(?P<key>.*?)(?P<operator> ?[NOT LIKE|LIKE|<=>|>=|<=|!=|<>|=|>|<] ?)(?P<values>.*)',text)
a.group(2) 组(2)
Output: 输出:
=
Since you mentioned whitespace(space, tab etc.) you can replace space with \\s
由于您提到了空格(空格,制表符等),因此可以将\\s
替换为空格
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.