【问题标题】:How to use RegEx in an if statement in Python?如何在 Python 的 if 语句中使用 RegEx?
【发布时间】:2019-08-26 18:30:18
【问题描述】:

我正在使用Kivy 使用re(正则表达式)执行类似“语法分析器”的操作。

我只想检查基本操作的有效语法(如 +|-|*|/|(|))。 用户将字符串(使用键盘)录制下来,然后我使用正则表达式对其进行验证。 但我不知道如何在 if 语句中使用正则表达式。我想要的是:如果用户带给我的字符串不正确(或不使用正则表达式检查)打印类似“inavlid string”的内容,如果正确则打印“Valid string”。

我试过了:

if re.match(patron, string) is not None:
    print ("\nTrue")
else:
    print("False")

但是,string 有什么并不重要,应用程序总是显示True

对不起,我糟糕的英语。任何帮助将不胜感激!

import  re

patron= re.compile(r"""

    (
    -?\d+[.\d+]?
    [+*-/]
    -?\d+[.\d+]?
    [+|-|*|/]?
    )*
    """, re.X)

obj1= self.ids['text'].text #TextInput
if re.match(patron, obj1) is not None:
    print ("\nValid String")
else:
    print("Inavlid string")

if obj1= "53.22+22.11+10*555+62+55.2-66" 实际上是正确的,并且应用程序会打印“有效...”,但是如果我像这样 "a53.22+22.11+10*555+62+55.2-66" 放置a,则它是不正确的,应用程序必须打印invalid..,但它仍然是valid

【问题讨论】:

标签: python regex


【解决方案1】:

这回答了您关于如何将 if 与正则表达式一起使用的问题:
警告:正则表达式公式不会清除所有无效输入,例如,两个小数点 (".. ")、两个运算符 ("++") 等。所以请调整它以满足您的确切需求)

import re

regex = re.compile(r"[\d.+\-*\/]+")

input_list = [
    "53.22+22.11+10*555+62+55.2-66", "a53.22+22.11+10*555+62+55.2-66",
    "53.22+22.pq11+10*555+62+55.2-66", "53.22+22.11+10*555+62+55.2-66zz",
]

for input_str in input_list:
    mmm = regex.match(input_str)
    if mmm and input_str == mmm.group():
        print('Valid: ', input_str)
    else:
        print('Invalid: ', input_str)

上面是一个用于单个字符串而不是列表的函数:

import re
regex = re.compile(r"[\d.+\-*\/]+")

def check_for_valid_string(in_string=""):
    mmm = regex.match(in_string)
    if mmm and in_string == mmm.group():
        return 'Valid: ', in_string
    return 'Invalid: ', in_string

check_for_valid_string('53.22+22.11+10*555+62+55.2-66')
check_for_valid_string('a53.22+22.11+10*555+62+55.2-66')
check_for_valid_string('53.22+22.pq11+10*555+62+55.2-66')
check_for_valid_string('53.22+22.11+10*555+62+55.2-66zz')

输出:

## Valid:  53.22+22.11+10*555+62+55.2-66
## Invalid:  a53.22+22.11+10*555+62+55.2-66
## Invalid:  53.22+22.pq11+10*555+62+55.2-66
## Invalid:  53.22+22.11+10*555+62+55.2-66zz

【讨论】:

    【解决方案2】:

    您的正则表达式始终匹配,因为它允许空字符串匹配(因为整个正则表达式都包含在一个可选组中。

    如果你测试这个live on regex101.com,你可以立即看到它,而且它不匹配整个字符串,而只匹配它的一部分。

    我已经更正了您的 character classes 中的两个错误,这些错误涉及使用不必要/有害的交替运算符 (|) 和破折号的不正确放置,使其成为范围运算符 (-),但它是仍然不正确。

    认为你想要更多这样的东西:

    ^               # Make sure the match begins at the start of the string
    (?:             # Start a non-capturing group that matches...
        -?          # an optional minus sign,
        \d+         # one or more digits
        (?:\.\d+)?  # an optional group that contains a dot and one or more digits.
        (?:         # Start of a non-capturing group that either matches...
           [+*/-]   # an operator
        |           # or
           $        # the end of the string.
        )           # End of inner non-capturing group
    )+              # End of outer non-capturing group, required to match at least once.
    (?<![+*/-])     # Make sure that the final character isn't an operator.
    $               # Make sure that the match ends at the end of the string.
    

    测试它live on regex101.com

    【讨论】:

    • 你们@Tim Pietzcker 是最棒的。我不知道那个语法 (?: xx )?做一些可选的事情。我已将 '+' 修改为 '*' 因为我的应用程序可以接受一个空字符串...现在我正在尝试添加 '(' ')' 以在其中进行操作,但我做不到.我尝试过类似的方法: ^ (?: -?\d+(?:\.\d+)? (?:[+*/-]|$) (?:(-?\d+(?:\.\ d+)?(?:[+*/-]|))))? )+ $ [链接]regex101.com/r/750sOO/5 但是不起作用。你能帮助我吗?只需要'(n (+|-|*|/) m)' 非常感谢
    • 一旦你使用括号(特别是因为它们可以任意嵌套),你就离开了正则表达式的领域。 Python 正则表达式不能递归或计算开/关括号。你需要一个上下文无关的语法/解析器。
    猜你喜欢
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    相关资源
    最近更新 更多