python - Python 正则表达式是否允许嵌入选项?

标签 python regex

特别是,我想知道我是否可以在模式字符串中指定一个嵌入选项来启用多行模式。也就是说,通常使用 Python 正则表达式多行模式是这样启用的:

pattern = re.compile(r'foo', re.MULTILINE)

我想要一种通过在模式字符串中指定多行匹配的方法,而不是使用 re.MULTILINE 选项。您可以在 Java 中使用嵌入式 (?m) 表达式执行此操作。例如,

pattern = re.compile(r'(?m)foo')

这在 Python 中是否可行,或者我是否需要使用 re.M 选项?一般来说,Python 中的嵌入式模式选项是否有很好的引用?

最佳答案

是的。

来自docs :

(?iLmsux) (One or more letters from the set 'i', 'L', 'm', 's', 'u', 'x'.)

The group matches the empty string; 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. (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 compile() function.

Note that the (?x) flag changes how the expression is parsed. 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.

关于python - Python 正则表达式是否允许嵌入选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/744885/

相关文章:

java - 用于替换的字符串正则表达式

python - sub ('a*|b' , '' , 'bcd' ) -> bcd WAT?

python - 在子类定义期间重新初始化父类属性

python - 如何通过远程服务器上的fabric替换文件字符串?

python - 将 pandas Series 作为列添加到 DataFrame 时出现 Wild NaN

python - OpenCV 分割轮廓

python - SublimeText2 插件设置 : Escape Dollar sign for a regex in DocBlockr plugin's settings

python - 存储要以加密形式存储的原始未加密文件的 sha256 哈希是否安全?

c# - 具有基本身份验证的 HTTP URL 的正则表达式

regex - 如何替换字符串中子字符串的所有实例