Julia 正则表达式
从实际文本中查找匹配、读取捕获组和字节偏移,并按条件替换。
学完这一章,你能够
- 从实际文本中查找匹配、读取捕获组和字节偏移,并按条件替换。
模式和查询分支
Julia 使用 PCRE 兼容的正则。r 字面量给出 Regex,模式内的反斜杠由正则引擎解释。按变量组装时可用 Regex 构造器,变量包含元字符时先决定是模式还是字面文本。
occursin 返回布尔值。match 返回第一个 RegexMatch,找不到时给 nothing。可从给定的有效字节下标开始搜索。eachmatch 可迭代全部不重叠匹配,设置 overlap=true 时也能观察重叠匹配。
捕获内容与位置
RegexMatch 的 match 字段是完整匹配,captures 包含各组子串。未参与匹配的可选组占一个位置,值为 nothing。offset 和 offsets 使用 Julia 字符串的代码单元下标,未匹配组的 offsets 项为 0。
捕获可用编号或 Symbol 名称访问,也能按组顺序解构。先检查 match 的返回值再取字段。使用中文前缀时,字符序号和字节偏移可能不同。
替换与标志
replace(s, pattern => replacement) 默认替换所有匹配,count=1 只替换第一处。s 字面量可在替换串内引用捕获,例如反斜杠 1 表示第一组,反斜杠 g<0> 表示整个匹配,反斜杠 g<name> 引用命名组。
i 控制大小写,m 使锚点可匹配每行的边界,s 让点号覆盖换行,x 可把表达式分行并加入注释。标志可合用,m 与 s 处理的是两类规则。
三个常见操作
| 操作 | 函数 | 结果 |
|---|---|---|
| 判断 | occursin | 得到 true 或 false。 |
| 查找 | match、eachmatch | 单项可能得到 nothing,多项用迭代器访问。 |
| 替换 | replace | 按匹配位置写入替换内容并返回字符串。 |
匹配对象
| 字段 | 内容与索引 |
|---|---|
| m.match | 整个匹配的子串。 |
| m.captures | 按组排列的子串。未参与匹配的组为 nothing。 |
| m.offset | 整个匹配的起始代码单元下标。 |
| m.offsets | 各组的起始代码单元下标,缺席组为 0。 |
修饰模式
| 标志 | 行为 |
|---|---|
| i | 忽略匹配时的大小写差异。 |
| m | 使 ^ 和 $ 可在行边界匹配。 |
| s | 让 . 也能匹配换行。 |
| x | 允许排版空白及注释,字符类和转义内另有规则。 |
文本实例:读取方向代码和捕获偏移
include(joinpath(@__DIR__, "observations.jl"))
heading = r"^\h*(?:#|$)"
probe("regex_literal", raw"^\h*(?:#|$)", (typeof(heading),typeof(Regex("^Track "*string(7))),occursin(Regex("^Track "*string(7)),"Track 7 north")),
(Regex,Regex,true))
probe("regex_occurs", ("station"," # station"," "), map(x -> occursin(heading,x),("station"," # station"," ")),
(false,true,true))
m = match(heading," # station")
classify(line) = match(heading,line) === nothing ? "data" : "heading"
probe("regex_match", ("station"," # station"), (match(heading,"station"),m.match,classify("station"),classify(" # station")),
(nothing," #","data","heading"))
text = "sea/N-7 N-21"
probe("regex_capture_text", "# wind report ",
only(match(r"^\s*#\s*(.*?)\s*$","# wind report ").captures), "wind report")
probe("regex_start_offset", (text,1,8,13),
(match(r"\d+",text,1).match,match(r"\d+",text,8).match,match(r"\d+",text,13)), ("7","21",nothing))
full = match(r"(N)(-)?(\d+)", "N-21")
short = match(r"(N)(-)?(\d+)", "海N21")
probe("regex_field_match", ("N-21","海N21"), (full.match,short.match),("N-21","N21"))
probe("regex_field_captures", ("N-21","海N21"), (full.captures,short.captures), (["N","-","21"],["N",nothing,"21"]))
probe("regex_field_offset", ("N-21","海N21"), (full.offset,short.offset),(1,4))
probe("regex_field_offsets", ("N-21","海N21"), (full.offsets,short.offsets),([1,2,3],[4,0,5]))
p1,p2,p3 = short
probe("regex_destructure", short.match, (p1,p2,p3),("N",nothing,"21"))
named = match(r"(?<site>[NS])-(?<count>\d+)","S-18")
probe("regex_named_capture", "S-18", (named[:site],named[:count],named[2]), ("S","18","18"))
samples = "海N-7 N-21"
items = collect(eachmatch(r"N-(\d+)",samples))
probe("regex_eachmatch", samples,
([(m.match,m.offset,only(m.offsets)) for m in items],collect(m.match for m in eachmatch(r"\d+",samples)),
length(collect(eachmatch(r"ana","banana"))),length(collect(eachmatch(r"ana","banana";overlap=true)))),
([("N-7",4,6),("N-21",8,10)],["7","21"],1,2))
probe("regex_replace", "a7b8c9", (replace("a7b8c9",r"\d"=>"#"),replace("a7b8c9",r"\d"=>"#";count=1)),
("a#b#c#","a#b8c9"))
probe("regex_substitute", ("north bay","Q","2026-07-18"),
(replace("north bay",r"(\w+) (?<zone>\w+)"=>s"\g<zone> \1"),
replace("Q",r"."=>s"\g<0>!"),
replace("2026-07-18",r"(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})"=>s"\g<d>/\g<m>/\g<y>")),
("bay north","Q!","18/07/2026"))
probe("regex_i", "NORTH", (occursin(r"^north$","NORTH"),occursin(r"^north$"i,"NORTH")),(false,true))
probe("regex_m", "head\nnorth\ntail", (occursin(r"^north$","head\nnorth\ntail"),
occursin(r"^north$"m,"head\nnorth\ntail")),(false,true))
probe("regex_s", "n\nh", (occursin(r"n.h","n\nh"),occursin(r"n.h"s,"n\nh")),(false,true))
pattern = r"""
([NS]) # site direction
- # separator
(\d+) # count
"""x
probe("regex_x", "N-37", match(pattern,"N-37").captures,["N","37"])
combined = match(r"^north.*south$"ims,"hdr\nNORTH\nsouth\nend")
probe("regex_combined", "hdr\\nNORTH\\nsouth\\nend", combined.match,"NORTH\nsouth")
- 在带中文前缀的示例中,两次匹配从第 4 与第 8 字节开始。缺席的可选组给 nothing 和 0。日期替换示例将 2026-07-18 改写为 18/07/2026。
所需环境:Julia 1.10.13 官方便携版,Windows x64,本机隔离目录
当前源码 SHA256:e7df0f3a2aac889b0dba0c9413b05ba029d138dcd4672a504af3623ae66f57b7
本机练习工程
解压后按 README 分别运行三个练习。脚本无需网络或额外包。
所需环境:Julia 1.10.13 官方便携版,Windows x64,本机隔离目录
ZIP SHA256:e89109dcec7b779e3f06229ca2b3692a1f69e851fd989a7d2325e074b7d4a5b2
常见错误与边界
- 需要按字面查找用户输入时,通常可用普通字符串搜索,直接拼接任意输入到正则会改变匹配语义。
练习与解答
为什么短样本里捕获组 2 的偏移是 0?
展开参考解答
模式中的连接符组是可选项,本次没有匹配。