简体   繁体   English

在python正则表达式中匹配表达式

[英]Matching an expression in python regex

I'm trying to match a coordinate with a python string regex, but I'm not getting a result. 我正在尝试将坐标与python字符串正则表达式进行匹配,但没有得到结果。 I was to see if the input is a valid coordinate definition but I'm not getting the correct match using the code below. 我正在查看输入是否为有效的坐标定义,但是使用下面的代码却找不到正确的匹配项。 Can someone tell me what's wrong? 有人可以告诉我怎么了吗?

def coordinate(coord):
     a = re.compile("^(([0-9]+), ([0-9]+))$")
     b = a.match(coord)
     if b:
         return True
     return False

Currently, it's returning false even if I pass in (3, 4) which is a valid coordinate. 目前,即使我传入(3, 4)这是一个有效的坐标,它也会返回false。

This works: 这有效:

from re import match
def coordinate(coord):   
    return bool(match("\s*\(\s*-?\d+(?:\.\d+)?\s*,\s*-?\d+(?:\.\d+)?\s*\)\s*$", coord))

It is also quite powerful, having the ability to handle negative numbers, fractions, and an optional space between the numbers. 它也非常强大,能够处理负数,分数和数字之间的可选空格。

Below is a breakdown of the Regex pattern: 以下是正则表达式模式的细分:

\s*         # Zero or more whitespace characters
\(          # An opening parenthesis
\s*         # Zero or more whitespace characters
-?          # An optional hyphen (for negative numbers)
\d+         # One or more digits
(?:\.\d+)?  # An optional period followed by one or more digits (for fractions)
\s*         # Zero or more whitespace characters
,           # A comma
\s*         # Zero or more whitespace characters
-?          # An optional hyphen (for negative numbers)
\d+         # One or more digits
(?:\.\d+)?  # An optional period followed by one or more digits (for fractions)
\s*         # Zero or more whitespace characters
\)          # A closing parenthesis
\s*         # Zero or more whitespace characters
$           # End of the string

You need to escape the parentheses that you are trying to match. 您需要转义要匹配的括号。 Try using the following: 尝试使用以下内容:

^(\([0-9]+,\s[0-9]+\))$

It seems to me that you do not properly escape the parenthesis that makes the coordinate syntax. 在我看来,您没有适当地避开构成坐标语法的括号。 In regex, parenthesis are special characters used for grouping and capturing . 在正则表达式中,括号是用于分组和捕获的特殊字符 You need to escape them this way: 您需要这样逃避它们:

>>> a = re.compile("^\(([0-9]+), ([0-9]+)\)$")
>>> a.match("(3, 4)")
<_sre.SRE_Match object at 0x0000000001D91E00>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM