RegExp 正则表达式类
RegExp 是 Alia 的内置正则表达式类,用于模式匹配、文本搜索和替换操作。
创建正则表达式
仅指定模式
const re = new RegExp ['\\d+']
指定模式与标志
const re = new RegExp ['hello', 'gi']
从对象创建
const re = new RegExp [*[pattern: '\\w+', flags: 'i']]
创建空正则
const re = new RegExp
实例属性(只读)
| 属性 | 类 型 | 说明 |
|---|---|---|
pattern | String | 正则模式字符串 |
flags | String | 标志字符串 |
global | Boolean | 是否设置 g 标志 |
multiline | Boolean | 是否设置 m 标志 |
ignoreCase | Boolean | 是否设置 i 标志 |
unicode | Boolean | 是否设置 u 标志 |
sticky | Boolean | 是否设置 y 标志 |
dotAll | Boolean | 是否设置 s 标志(. 匹配换行符) |
实例方法
test
测试字符串是否匹配正则表达式,签名为 re.test input,接收单个字符串参数并返回 Boolean。
const re = new RegExp ['\\d+']
print re.test 'abc123' ~ true
print re.test 'abc' ~ false
exec
执行匹配搜索,签名为 re.exec input,接收单个字符串参数,无匹配返回 Null,有匹配返回详情对象。
const re = new RegExp ['(\\d+)-(\\d+)']
const m = re.exec '2024-01-15'
if typeOf m == 'Object' {
print m.index ~ 0
print m.matched ~ '2024-01'
print m.groups ~ ['2024', '01']
}
返回值结构:*[index: Number, matched: String, groups: Array]
match
签名为 re.match input,接收单个字符串参数并返回匹配结果,无匹配返回 Null。
非全局模式返回嵌套单元素数组:
const re1 = new RegExp ['\\d+']
print re1.match 'a12b' ~ [[*[index: 1, matched: '12', groups: []]]]
全局模式返回全部匹配结果:
const re2 = new RegExp ['\\d+', 'g']
print re2.match 'a12b34' ~ [*[index: 1, matched: '12', groups: []], *[index: 4, matched: '34', groups: []]]
replace
替换匹配的内容,签名为 re.replace input with replacement,接收输入字符串并以 with 连接替换字符串,返回 String。
const re = new RegExp ['\\d+']
print re.replace 'a12b34' with 'X' ~ 'aXb34'
const re2 = new RegExp ['\\d+', 'g']
print re2.replace 'a12b34' with 'X' ~ 'aXbX'
split
按模式分割字符串,签名为 re.split input,接收输入字符串并返回 Array。
const re = new RegExp [',\\s*']
print re.split 'a, b, c' ~ ['a', 'b', 'c']
可指定返回结果数量限制,以 limit 连接上限:
const re = new RegExp [',\\s*']
print re.split 'a, b, c, d' limit 2 ~ ['a', 'b']
静态方法
RegExp.escape
转义字符串中的正则特殊字符,签名为 RegExp.escape input,接收单个字符串参数并返回 String。
const escaped = RegExp.escape 'price: $10.00'
print escaped ~ 'price: \$10\.00'
完整示例
~ 创建正则
const email = new RegExp ['[\\w.]+@[\\w.]+\\.[a-z]{2,}', 'i']
const digits = new RegExp ['\\d+', 'g']
~ 测试匹配
print email.test 'user@example.com' ~ true
~ 替换
print digits.replace 'abc 123 def 456' with '#' ~ 'abc # def #'
~ 分割
const sep = new RegExp [',\\s*']
const parts = sep.split 'a, b, c'
print parts ~ ['a', 'b', 'c']
~ 匹配
const matcher = new RegExp ['\\d+', 'g']
const nums = matcher.match 'a12b34'
print nums ~ [*[index: 1, matched: '12', groups: []], *[index: 4, matched: '34', groups: []]]
~ exec
const re = new RegExp ['(\\d+)-(\\d+)']
const m = re.exec '2024-01-15'
if typeOf m == 'Object' {
print m.index ~ 0
print m.matched ~ '2024-01'
print m.groups ~ ['2024', '01']
}
~ 属性
print email.global ~ false
print email.ignoreCase ~ true
print email.pattern ~ '[\\w.]+@[\\w.]+\\.[a-z]{2,}'
~ 静态方法
print RegExp.escape '$10.00' ~ '\\$10\\.00'
标志说明
| 标志 | 属性名 | 说明 |
|---|---|---|
g | global | 全局匹配 |
i | ignoreCase | 忽略大小写 |
m | multiline | 多行模式 |
s | dotAll | . 匹配换行符 |
u | unicode | Unicode 模式 |
y | sticky | 粘性匹配 |