Skip to main content
 首页 » 编程设计

python之验证 json 中指定的 python 正则表达式标志

2025年02月15日29zhujiabin

我正在编写一个通过 json 文件接受用户配置的工具。此配置的一部分是 python 正则表达式和一些可选的正则表达式标志。目前正则表达式标志的配置是一个整数数组,它们将全部通过按位或 (|) 运行并发送到重新编译方法。

我的问题是如何验证这些整数以确保它们是有效的重新标记?

编辑:或者可能是我的问题的另一种解决方案……用户是否可以在 JSON 中指定实际的 re 标志?即,[re.DEBUG、re.IGNORECASE] 等等,然后以某种方式从我的 python 脚本中的 JSON 文件翻译这些内容?

请您参考如下方法:

你可以定义一个包含所有可能标志的字典(它们真的很少,参见re 6.2.2. Module Contents ),然后通过相应的键获取值即可。

A Python demo :

import re 
re_flags = { 're.A' : re.A,  
    're.ASCII' : re.ASCII, 
    're.DEBUG' : re.DEBUG, 
    're.I' : re.I, 
    're.IGNORECASE' : re.IGNORECASE, 
    're.L' : re.L, 
    're.LOCALE' : re.LOCALE, 
    're.M' : re.M, 
    're.MULTILINE' : re.MULTILINE, 
    're.S' : re.S, 
    're.DOTALL' : re.DOTALL, 
    're.X' : re.X, 
    're.VERBOSE' : re.VERBOSE } 
flg = 're.I'                      # User input 
if flg in re_flags:               # If the dict contains the key 
    print(re_flags[flg])          # Print the value (re.I = 2) 

如果您仍然想改用数字:

import re 
print(re.A)           # 256 
print(re.ASCII)       # 256 
print(re.DEBUG)       # 128 
print(re.I)           # 2 
print(re.IGNORECASE)  # 2 
print(re.L)           # 4 
print(re.LOCALE)      # 4 
print(re.M)           # 8 
print(re.MULTILINE)   # 8 
print(re.S)           # 16 
print(re.DOTALL)      # 16 
print(re.X)           # 64 
print(re.VERBOSE)     # 64