验证json中指定的python regex标志

2024-04-26 12:52:43 发布

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

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

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

或者我的问题的另一个解决方案。。。用户是否可以在JSON中指定实际的re标志?即[重新调试, 忽略案例]等等,然后从我的python脚本中的JSON文件中翻译出来?你知道吗


Tags: 文件工具方法用户标记re脚本json
1条回答
网友
1楼 · 发布于 2024-04-26 12:52:43

您可以定义一个包含所有可能标志的字典(它们确实很少,请参见re6.2.2. Module Contents),只需通过相应的键获取值。你知道吗

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

相关问题 更多 >