首页 > 解决方案 > 如何使用 Python 使用正则表达式在字符串中搜索/查找特殊字符,如 &、< 或 >

问题描述

嗨,我正在 python 中编写一个函数来使用正则表达式在文本字符串中搜索特殊字符。

一旦找到匹配项,程序应该给出错误信息并退出。

这就是我到目前为止所做的并且能够搜索 ;,$,%,' 但无法在 Windows 中搜索和查找 &、<、> 之类的字符。

下面给出的当前代码适用于 Windows,但不适用于 Linux。但我想在 Windows 以及 Linux 中使用此代码。

这是我的代码:

#tests for finding special characters

import sys, re


cmd = input('Enter your command : ')


def chk_cmds(cmd):
    print('chk_cmds: lets look term at %s' % (cmd))
    msg = bool(re.search(r'\;|\$|\%|`', cmd))
    if msg is True:
        print(msg)
        print('Found a suspicious entry in the command : ' + cmd)
        print('Exiting the program')
        return -1
        sys.exit
    else:
        print('Command seems clean ' +cmd)
        return 0
    # return -1

chk_cmds(cmd)

问:在 Windows 和 Linux 中,我如何还能在字符串中搜索特殊字符,如 &、<、>。

我已经尝试为每个字符使用反斜杠转义字符

喜欢 bool(re.search(r'\;|\$|\%|`|\&|\<|\>', cmd)),但 re.search 没有在 Windows 中找到它们。(而且下面的当前代码似乎在 Linux 中不起作用)

标签: pythonregex

解决方案


如果您遍历输入字符串的每个字符并将其 ASCII 代码与您希望它检测的 ASCII 代码列表进行比较。

import sys, re
cmd = input('Enter your command : ')
def chk_cmds(cmd):
    print('chk_cmds: lets look term at %s' % (cmd))
    # ASCII codes for the special characters you specified:
    bad_chars = [36, 37, 38, 59, 60, 62, 63, 96]
    msg = False
    for letter in cmd:
        for i in bad_chars:
            if(ord(letter) == i):
                msg = True
    if msg is True:
        print(msg)
        print('Found a suspicious entry in the command : ' + cmd)
        print('Exiting the program')
        return -1
        sys.exit
    else:
        print('Command seems clean ' +cmd)
        return 0
    # return -1
chk_cmds(cmd)

这适用于我在 Linux 上使用 python3


推荐阅读