python - 如何使用 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 中不起作用)
解决方案
如果您遍历输入字符串的每个字符并将其 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
推荐阅读
- python - 比较 2 个文件并返回不同的带有标签的文件
- linux - 无法找到 GPU Nvidia GeForce 的软件包 vulkan?
- html - 将一个 div 的值加载到另一个
- r - 在 R 中以编程方式创建图矩阵
- r - 如何在 R 中使用 url?
- vba - 在 Access-VBA 中创建数据库副本不起作用
- django - 制作了一个应用程序并希望在其他应用程序中访问其模型并希望限制用户注册以访问网站
- java - 来自无害语句的 Java 14 VerifyError
- python - Python数组跳过索引的问题
- angular - 将 Angular Pipe 应用于 Angular 递归列表模板