首页 > 解决方案 > 您将如何为输入验证编写正则表达式以使某些符号不能重复?

问题描述

我正在尝试编写一个正则表达式来防止某些用户在数学表达式中输入。(例如,“1+1”是有效的,而“1++1”应该是无效的)可接受的字符包括*digits 0-9* (\d works in lieu of 0-9), + - # / ( ) and white-spaces.

我试图组合一个正则表达式,但我在 python 正则表达式语法中找不到任何可以验证的东西(或者因此在一起输入时使某些字符无效。 (( is ok ++, --, +-, */, are not

我希望有一种简单的方法可以做到这一点,但我预计如果没有,我将不得不为我不想允许在一起的每个可能的字符组合编写正则表达式。

我试过了:

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

如果有人输入“1++1”,我希望能够使表达式无效

编辑:Someone suggested the below link is similar to my question...it is not :)

使用正则表达式验证数学表达式?

标签: regexpython-2.7

解决方案


也许一种选择可能是检查字符串是否有不需要的组合:

[0-9]\s*(?:[+-][+-]|\*/)\s*[0-9]

正则表达式演示| Python 演示

例如

pattern = r"[0-9]\s*(?:[+-][+-]|\*/)\s*[0-9]"
strings = [
    'This is test 1 -- 1',
    'This is test 2',
    'This is test 3+1',
    'This is test 4 */4'
    ]

for s in strings:
    res = re.search(pattern, s)
    if not res:
        print("Valid: " + s)

结果

Valid: This is test 2
Valid: This is test 3+1

推荐阅读