01
入门
基础语法
正则表达式使用特殊字符进行模式匹配。. 匹配任意字符,[] 定义字符类,\d \w \s 是常用字符集的简写。在 [] 内使用 ^ 表示取反。
regex
# Basic matching
hello # literal match
. # any character except newline
[abc] # any of a, b, c
[^abc] # not a, b, or c
[a-z] # range a to z
\d # digit [0-9]
\D # non-digit
\w # word char [a-zA-Z0-9_]
\W # non-word char
\s # whitespace
\S # non-whitespace元字符
元字符具有特殊含义。要字面匹配它们,请加反斜杠前缀。在字符类 [] 内,只有 ] \ ^ 和 - 需要转义(且 - 仅在不处于开头/结尾时需要)。
regex
# Special metacharacters that need escaping:
. * + ? ^ $ { } [ ] \\ | ( )
# Escape with backslash to match literally
\. # literal dot
\* # literal asterisk
\+ # literal plus
\? # literal question mark
\( # literal parenthesis
\[ # literal bracket
\$ # literal dollar
\^ # literal caret
\\ # literal backslash
# Example: match "1.5" not "1x5"
1\.5 # matches "1.5" only点号与通配符
点号 . 默认匹配除换行符外的任意字符。使用 s 标志(dotall 模式)可让 . 匹配包括换行符在内的所有字符。点号在字符类 [] 内是字面量,无需转义。
regex
# Dot matches any char except newline (by default)
a.c # matches "abc", "a c", "a1c", "a@c"
a..c # four chars: a, any, any, c
# Dot matches newline only with /s flag (dotall)
/a.b/s # "a\nb" matches
# Match any character truly (with /s flag)
/[\s\S]/ # any char including newline (portable)
/[\d\D]/ # also any char
/[\w\W]/ # also any char
# Practical: any chars between tags
<div[\s\S]*?</div>代码中的正则字面量
JavaScript 支持 /pattern/flags 字面量语法;Python/Java 使用字符串构造。字面量形式更易读且无需双重转义,但无法在运行时动态构建。字符串形式需要双重转义反斜杠(如 \\d)。
regex
# JavaScript - regex literal
const re = /\bword\b/gi;
# JavaScript - constructor (for dynamic patterns)
const re2 = new RegExp("\\bword\\b", "gi");
# Python - raw string with re module
import re
pattern = r"\bword\b"
re.search(pattern, "a word here")
# Java - String needs double escaping
Pattern p = Pattern.compile("\\bword\\b");
# PHP - Perl-style
if (preg_match('/\\bword\\b/i', $text)) { }
# Go - RE2 syntax
re := regexp.MustCompile(`\\bword\\b`)测试与匹配
test() 返回布尔值,exec() 返回匹配详情(包括捕获组)。match() 在没有 g 标志时返回类 exec 结果,有 g 标志时返回所有匹配数组。matchAll() 返回迭代器,需配合 g 标志使用。
regex
# JavaScript
/abc/.test("abcdef") # true
"abcdef".match(/abc/) # ["abc", index: 0]
"abcabc".match(/abc/g) # ["abc", "abc"]
"abcdef".search(/abc/) # 0 (index)
# Python
import re
re.search(r"abc", "abcdef") # Match object or None
re.match(r"abc", "abcdef") # anchored at start
re.fullmatch(r"abc", "abc") # entire string
# Test if pattern matches anywhere
bool(re.search(r"abc", "xabcx")) # True02
字符类
字符集合 [abc]
方括号定义字符集合,匹配其中任意一个字符。顺序无关。常见用途:元音 [aeiou]、十六进制 [0-9a-fA-F]。在集合内,大多数元字符变为字面量。
regex