3

所以我有一个 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 文件中定义的正则表达式来搜索字符串?

4

3 回答 3

4

我在我的 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)$')}
于 2015-04-22T21:16:17.183 回答
3

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

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

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

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

于 2012-05-27T02:14:57.767 回答
3

您在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]'

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

于 2012-05-27T02:17:22.183 回答