简体   繁体   English

如何在 Python 3 中的 assertRegex 中表达多行正则表达式?

[英]How can I express a multi-line regex in assertRegex in Python 3?

I'm using the assertRegex() function from the unittest library in Python 3.4.我正在使用 Python 3.4 中单元测试库中的unittest () function It only takes two relevant parameters: the text to match against and the regex.它只需要两个相关参数:要匹配的文本和正则表达式。 The seems to prevent me from expressing any regex-related constants such as re.MULTILINE .这似乎阻止我表达任何与正则表达式相关的常量,例如re.MULTILINE

How can I construct or specify a multi-line regex and use it with assertRegex() ?如何构建或指定多行正则表达式并将其与assertRegex()一起使用? Alternatively, is there a related way of solving my problem?或者,是否有解决我的问题的相关方法?

See here in the Python docs: 这里的Python文档:

(?iLmsux)

(One or more letters from the set 'i', 'L', 'm', 's', 'u', 'x'.) The group matches the empty string; (来自集合'i','L','m','s','u','x'的一个或多个字母。)该组匹配空字符串; the letters set the corresponding flags: re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), re.U (Unicode dependent), and re.X (verbose), for the entire regular expression. 字母设置相应的标志:re.I(忽略大小写), re.L (依赖于语言环境), re.M (多行), re.S (点匹配所有), re.U (取决于Unicode),以及re.X (详细),用于整个正则表达式。 (The flags are described in Module Contents.) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the re.compile() function. (标志在模块内容中描述。)如果您希望将标志包含在正则表达式的一部分中,而不是将标志参数传递给re.compile()函数,这将非常有用。

Note that the (?x) flag changes how the expression is parsed. 请注意, (?x)标志会更改表达式的解析方式。 It should be used first in the expression string, or after one or more whitespace characters. 它应该首先在表达式字符串中使用,或者在一个或多个空格字符之后使用。 If there are non-whitespace characters before the flag, the results are undefined. 如果标志前面有非空白字符,则结果未定义。

One way is to construct Regexp with re.compile ( Official Python 3 reference ).一种方法是使用re.compile构建 Regexp(官方 Python 3 参考)。 An example is一个例子是

self.assertRegex(str1, re.compile('\\bcd '+re.escape(os.getcwd())+'\n', re.M | re.I))

This is useful when the expression is complex.这在表达式复杂时很有用。

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

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