繁体   English   中英

Python 从 yaml 配置文件解释正则表达式

[英]Python interpreting a Regex from a yaml config file

所以我有一个 yaml 文件,用作配置文件。 我正在尝试使用正则表达式进行一些字符串匹配,但是我无法将正则表达式从 yaml 解释为 python。 有问题的正则表达式如下所示:

regex:
    - [A-Za-z0-9]

当我尝试使用re.match函数时,出现此错误:

Traceback (most recent call last):
  File "./dirpylint.py", line 132, in <module>
    sys.exit(main())
  File "./dirpylint.py", line 32, in main
    LevelScan(level)
  File "./dirpylint.py", line 50, in LevelScan
    regex_match(level)
  File "./dirpylint.py", line 65, in regex_match
    if re.match(expression, item) == None:
  File "/usr/lib/python2.7/re.py", line 137, in match
    return _compile(pattern, flags).match(string)
  File "/usr/lib/python2.7/re.py", line 229, in _compile
    p = _cache.get(cachekey)
TypeError: unhashable type: 'list'

我知道它将正则表达式解释为列表,但是我将如何使用 yaml 文件中定义的正则表达式来搜索字符串?

我在我的 YAML 解析“引擎”中做到了这一点。

In [1]: from StringIO import StringIO
In [2]: import re, yaml
In [3]: yaml.add_constructor('!regexp', lambda l, n: re.compile(l.construct_scalar(n)))
In [4]: yaml.load(StringIO("pattern: !regexp '^(Yes|No)$'"))
Out[4]: {'pattern': re.compile(ur'^(Yes|No)$')}

如果您想使用 safe_load 和 !!python/regexp(类似于 ruby​​ 和 nodejs 的实现),这也有效:

In [5]: yaml.SafeLoader.add_constructor(u'tag:yaml.org,2002:python/regexp', lambda l, n: re.compile(l.construct_scalar(n)))
In [6]: yaml.safe_load(StringIO("pattern: !!python/regexp '^(Yes|No)$'"))
Out[6]: {'pattern': re.compile(ur'^(Yes|No)$')}

问题是 YAML,而不是 Python。
如果要在 YAML 文件中存储包含文字方括号的字符串值,则必须引用它:

regex:
  - '[A-Za-z0-9]'

使用“单引号”意味着 YAML 不会解释正则表达式中的任何反斜杠转义序列。 例如\\b

另请注意,在此 YAML 中, regex的值是一个包含一个字符串的列表,而不是一个简单的字符串。

您在YAML文件中使用了两个列表结构。 加载YAML文件时:

>>> d = yaml.load(open('config.yaml'))

你得到这个:

>>> d
{'regex': [['A-Za-z0-9']]}

请注意,正则表达式中的方括号实际上正在消失,因为它们被识别为列表分隔符。 你可以引用它们:

正则表达式:-“[A-Za-z0-9]”

要得到这个:

>>> yaml.load(open('config.yaml'))
{'regex': ['[A-Za-z0-9]']}

所以正则表达式是d['regex'][0] 但是您也可以在yaml文件中执行此操作:

regex: "[A-Za-z0-9]"

这让你:

>>> d = yaml.load(open('config.yaml'))
>>> d
{'regex': '[A-Za-z0-9]'}

因此,可以使用类似的字典查找来检索正则表达式:

>>> d['regex']
'[A-Za-z0-9]'

...这可以说要简单得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM