笔记一

笔记源自 RegexOne

需要转义的特殊字符: * . ? + $ ^ [ ] ( ) { } | \ /

  • \s 匹配所有空格字符,等同于: [\t\n\f\r\p{Z}]
  • \f 换页符
  • \n 换行符
  • \r 回车符
  • \t 制表符
  • \p 等同于\r\n, CRLF DOS 行终止符

Notes

非捕获组:

(?:...): 匹配字符但不创建捕获组

下面的笔记源自 github 正则表达式教程

4. 零宽度断言

正先行断言 (positive lookahead):(?=...),匹配位置的后面有指定模式

负先行断言 (negative lookahead):(?!...),匹配位置的后面没有指定模式

正后发断言 (positive lookbehind):(?<=...) 匹配位置的前面有指定模式

负后发断言 (negative lookbehind):(?<!...) 匹配位置的前面没有指定模式

比如对于字符串 foobarbarfoo

bar(?=bar)     finds the 1st bar ("bar" which has "bar" after it)
bar(?!bar)     finds the 2nd bar ("bar" which does not have "bar" after it)
(?<=foo)bar    finds the 1st bar ("bar" which has "foo" before it)
(?<!foo)bar    finds the 2nd bar ("bar" which does not have "foo" before it)
(?<=foo)bar(?=bar)    finds the 1st bar ("bar" with "foo" before it and "bar" after it)

5. 标志

/pattern/flags, 其中 flags 有:

  • i 忽略大小写。
  • g 全局搜索,返回全部匹配。
  • m 多行修饰符:锚点元字符 ^ $ 工作范围在每行的起始。

6. 贪婪匹配和惰性匹配

默认是贪婪匹配,使用?转化为惰性匹配。

"/(.*at)/" => The fat cat sat on the mat. "/(.*?at)/" => The fat cat sat on the mat.