How do you match a user-defined label literally inside a pattern?

escape quotes characters with special pattern meanings so literal text can be embedded in a regular expression.

Python example and interpretation

A plus in the label a+b must match a literal plus. This escaping is for a pattern; replacement strings follow their own rules.

import re
pattern=re.escape('a+b')
[bool(re.fullmatch(pattern,s)) for s in ['a+b','aaab']]

Result [True, False]

中文

怎样把用户自定义标签按字面加入匹配规则?

escape 对模式中具有特殊含义的字符做转义,适合把普通文本嵌入正则表达式。

Python 算例与适用条件

标签 a+b 中的加号应当只匹配加号。这个转义规则用于模式文本,替换文本有自己的处理规则。

import re
pattern=re.escape('a+b')
[bool(re.fullmatch(pattern,s)) for s in ['a+b','aaab']]

结果 [True, False]

References / 参考来源

Keep reading / 继续阅读