-1

我正在尝试使用 Python re 来测试字符串中除数字和破折号以外的任何内容。所以只有这样的字符串会通过:“1-2-3-4”

问题是,它说字符串“1-0-0-0”包含不允许的内容。无论我扔什么,它似乎都会返回 True 。“asdf”、“asdf%”、“1-0-0-0”都返回 True。我从来没有真正擅长正则表达式。

谁能确定我的模式有什么问题?

def checkStringForUnallowables(test):
    # Returns False if the string passes the unallowables check
    stringCheck = re.compile('[abcdefghijklmnopqrstuvwxyz@_!#$%^&*()<>?/\|}{~:]')

    # Pass the string in search function of RE object (string_check):
    if(stringCheck.search(test) == None):
        print("String does not contain unallowables - returning False")
        return False
    else:
        print("String contains unallowables - returning True")
        return True
4

2 回答 2

0

您只需要更改 if 条件

import re

def checkStringForUnallowables(test):
    stringCheck = re.compile('[abcdefghijklmnopqrstuvwxyz@_!#$%^&*()<>?/\|}{~:]')

    if not stringCheck.search(test):
        print("String does not contain unallowables - returning False")
        return False
    else:
        print("String contains unallowables - returning True")
        return True
于 2020-06-19T15:30:44.220 回答
0

将正则表达式字符串更改为 [^\d-] 最终可以工作。

于 2020-06-19T16:48:35.137 回答