gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:35:44 27 4
gpt4 key购买 nike

特别是,我想知道我是否可以在模式字符串中指定一个嵌入选项来启用多行模式。也就是说,通常使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com