目录:
1. 修饰符概述
正则表达式修饰符(也称 “标记” 或 “flags”)用于改变正则表达式的匹配行为。例如,可以让匹配忽略大小写、进行全局搜索、支持多行匹配等。
在不同的编程语言中,修饰符的使用方式可能有所不同,例如:
- 在 JavaScript 中,修饰符作为正则表达式的后缀,如:
/pattern/ig
- 在 Python 中,修饰符作为
re
模块的参数,如:re.compile(pattern, re.IGNORECASE)
2. 常见修饰符
i
– 忽略大小写
作用: 让匹配不区分大小写。
示例:
1 2 | const regex = /hello/i; console.log(regex.test("Hello")); // true |
1 2 | import re print(bool(re.search(r"hello", "Hello", re.IGNORECASE))) # True |
应用场景: 适用于搜索不区分大小写的文本,如 email
、username
等。
g
– 全局匹配
作用: 查找所有匹配项,而不仅仅是第一个。
示例:
1 2 | const regex = /cat/g; console.log("cat cat cat".match(regex)); // ["cat", "cat", "cat"] |
Python 没有
g
修饰符,可以用 re.findall()
或 re.finditer()
实现:
1 2 | import re print(re.findall(r"cat", "cat cat cat")) # ['cat', 'cat', 'cat'] |
应用场景: 需要提取多个匹配结果时使用。
m
– 多行模式
作用: 影响 ^
和 $
,使其匹配每一行的开头和结尾,而不是整个字符串的开头和结尾。
示例:
1 2 | const regex = /^hello/m; console.log("hello world\nhello again".match(regex)); // ["hello"] |
1 2 3 | import re text = "hello world\nhello again" print(re.findall(r"^hello", text, re.MULTILINE)) # ['hello', 'hello'] |
应用场景: 解析多行日志、配置文件等。
s
– 单行模式(dotAll)
作用: 让 .
(通配符)匹配换行符 \n
,默认情况下 .
不能匹配换行符。
示例:
1 2 | const regex = /hello.*world/s; console.log("hello\nworld".match(regex)); // ["hello\nworld"] |
1 2 3 | import re text = "hello\nworld" print(re.search(r"hello.*world", text, re.DOTALL)) # <match object> |
应用场景: 需要匹配包含换行符的内容,如 HTML 代码、日志文件等。
u
– Unicode 模式
作用: 让 \w
, \d
, \s
等字符类支持 Unicode 字符匹配。
示例:
1 2 | const regex = /\p{L}+/gu; // 仅 JavaScript ES6+ 支持 console.log("你好 world".match(regex)); // ["你好", "world"] |
Python 默认支持 Unicode,但 re.ASCII
让其仅匹配 ASCII 字符:
1 2 3 | import re print(re.findall(r"\w+", "你好 world")) # ['你好', 'world'] print(re.findall(r"\w+", "你好 world", re.ASCII)) # ['world'] |
应用场景: 处理多语言文本,如匹配中文、日文、阿拉伯文等。
y
– 粘性匹配
作用: 从字符串的当前索引开始匹配,不会回溯。
示例(仅 JavaScript 支持):
1 2 3 | const regex = /hello/y; regex.lastIndex = 6; console.log(regex.test("hello hello")); // true |
Python 没有 y
,但 \G
可用于模拟部分粘性匹配:
1 2 3 | import re pattern = re.compile(r"\Ghello") print(pattern.findall("hello hello")) # ['hello'] |
应用场景: 逐步解析字符串,如解析 JSON、语法分析等。
3. 修饰符的组合使用
多个修饰符可以同时使用,例如:
gi
(全局+忽略大小写)ms
(多行+单行)
示例:
1 2 | const regex = /hello/gi; console.log("Hello hello HELLO".match(regex)); // ["Hello", "hello", "HELLO"] |
1 2 | import re print(re.findall(r"hello", "Hello hello HELLO", re.IGNORECASE)) # ['Hello', 'hello', 'HELLO'] |
4. 参考资料
出站链接
站内链接
这样整理后,你觉得是否符合你的需求?
发表回复