Python正则表达式未标识\%和\^

2024-06-24 12:27:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试识别集合{@,$,!,%中的无效元字符&;,^}。 下面是Python3代码:

import re
def _getHTML(input):
        if re.search(r'(\!|\@|\#|\$|\%\^)', input) is not None:
            raise Exception('Invalid metacharacter found:(@,$,!,%,&,^)')
        else:
            print("passed")

但是,getHTML('eee e rwer %')在由于“%”而引发错误时,会导致“passed”


Tags: 代码importrenoneinputsearchifis
1条回答
网友
1楼 · 发布于 2024-06-24 12:27:20

正则表达式模式中的|(或)后面缺少\%

(\!|\@|\#|\$|\%|\^)

但是,您可以使用character类,而不是OR-ing和needness-grouping(因为您在后面没有提到它):

[!@#$%^]

您也可以在[]内摆脱\逃逸

相关问题 更多 >