常量表示方法:/pattern/gim 。
方法/属性 | 意义 |
---|---|
("正则表达式","参数") | 初始化对象可选参数 |
source | 正则表达式 pattern 部分 |
regExp.compile(pattern, [flags]) | 将 pattern 转换为内部版本,在循环中加快执行速度 |
exec(str) | 查找匹配,返回 结果数组,没有找到返回 null |
test(str) | 查找匹配,返回 TRUE 或 FALSE |
静态变量,每次匹配操作后记录。
属性 | 简写 | 意义 | 初始值 |
---|---|---|---|
index | 匹配的位置,第一个位置为 0 | "undefined" | |
lastIndex | 匹配的下个字符位置 | "undefined" | |
lastMatch | $& | 最近匹配的字符串 | 空字符串 |
lastParen | $+ | 最近子匹配的字符串 | 空字符串 |
leftContext | 位于匹配左边的字符串 | 空字符串 | |
rightContext | 位于匹配右边的字符串 | 空字符串 | |
$1 - $9 | $1 - $9 | 捕获的各个匹配 | 空字符串 |
input | 上次被查找的字符串 | 空字符串 |
值 | 意义 |
---|---|
"i" | 不计大小写 |
"g" | 匹配/替换 所有 |
"m" | 多行 匹配/替换 |
方法 | 意义 |
---|---|
search(regExp) | 查找匹配的第一个位置,没有则返回 -1 |
replace(regExp,str) | 查找匹配并用 str 替换,返回字符串 |
match(regExp) | 查找匹配,返回 结果数组,没有找到返回 null |
exec 函数
match 函数
属性 | 意义 |
---|---|
length | 数组大小 |
input | 被查找的源字符串 |
index | 匹配位置,从 0 开始 |
lastindex | 匹配字符串之后的位置 |
下标为 0 | 整个匹配字符串 |
下标为 1-n | 子匹配字符串 |
替换操作,将连续重复的单词替换为一个:
"A a bb bb bb cc cc cc cc ddd e e.\n".replace(/\b([a-z]+)( +\1)+\b/gim,"$1") // (\b([a-z]+) 表示一个单词 // ( +\1)+ 表示多个空格及多个重复单词 // \b 表示单词间隔,避免匹配单词的前面一部分 // RegExp.$1 为 (\b[a-z])+),现在为"e" // RegExp.$2 为 ( +\1),现在为"e" |
查找匹配,返回匹配内容及位置:
s = "---tc---TC---Ttc---tTc---TC---Tc---";
reg = new RegExp("t+c","gi"); n = 0; do { r = reg.exec(s); if(r==null) break; n++; addr = RegExp.lastIndex - r[0].length; document.write("在位置" + addr + "发现匹配:" + r + "<br>"); }while(true); document.write("在字符串:" + s + "<br>中发现字符串:"); document.write(reg.source + "<br>共计:" + n + "个."); |