TL
Tool Lab
💰捐赠
💰捐赠

正则表达式参考

正则表达式语法快速参考指南,包括字符类、锚点、量词、分组、标志和常用模式。

字符类

.Any character except newline
\wWord character [a-zA-Z0-9_]
\WNon-word character
\dDigit [0-9]
\DNon-digit
\sWhitespace (space, tab, newline)
\SNon-whitespace
[abc]Character class — a, b, or c
[^abc]Negated class — not a, b, or c
[a-z]Range — any lowercase letter
[a-zA-Z0-9]Alphanumeric characters

锚点

^Start of string (or line with multiline)
$End of string (or line with multiline)
\bWord boundary
\BNon-word boundary
\AStart of string (not multiline)
\ZEnd of string (not multiline)

量词

*Zero or more (greedy)
+One or more (greedy)
?Zero or one (greedy)
{n}Exactly n times
{n,}n or more times
{n,m}Between n and m times
*?Zero or more (lazy/non-greedy)
+?One or more (lazy/non-greedy)
??Zero or one (lazy/non-greedy)

分组与选择

(abc)Capture group
(?:abc)Non-capturing group
(?P<name>abc)Named capture group
a|bAlternation — a or b
(?=abc)Positive lookahead
(?!abc)Negative lookahead
(?<=abc)Positive lookbehind
(?<!abc)Negative lookbehind

转义与特殊字符

\nNewline
\tTab
\rCarriage return
\0Null character
\uXXXXUnicode character (hex)
\.Literal dot (escaped)
\\Literal backslash

标志

gGlobal — find all matches
iCase-insensitive
mMultiline — ^ and $ match line start/end
sDotall — . matches newline
uUnicode — treat pattern as Unicode
ySticky — match from lastIndex

常用模式

^[\w.-]+@[\w.-]+\.\w{2,}$Email address
https?://[\w./%-]+URL (basic)
^\d{1,3}(\.\d{1,3}){3}$IPv4 address
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$Hex color
^\d{4}-\d{2}-\d{2}$ISO date (YYYY-MM-DD)
^[+]?[\d\s()-]{7,15}$Phone number (basic)
^(?=.*[A-Z])(?=.*\d).{8,}$Password: 8+ chars, 1 uppercase, 1 digit

关于本工具

正则表达式是描述字符串模式的强大语言。本参考涵盖最常用的语法和模式。

按类别分节整理,可使用搜索框通过关键词快速过滤模式。

使用方法

  1. 浏览各节查找所需语法。
  2. 使用搜索框按关键词过滤。
  3. 点击任意模式将其复制到剪贴板。
  4. 在正则表达式测试工具中测试模式。

使用场景

适用于表单验证、字符串解析、日志分析、查找替换等各种编程任务。

常见问题

  • 正则表达式在所有语言中都适用吗?大多数语言支持正则表达式,但语法略有差异。JavaScript、Python、Java等主要语言大多遵循PCRE兼容语法。
  • 如何进行大小写不敏感匹配?在模式后添加i标志。例如:/pattern/i
  • 贪婪量词和懒惰量词有什么区别?贪婪量词(*, +, ?)尽可能多地匹配,懒惰量词(*?, +?, ??)尽可能少地匹配。