String 中的正则表达式
视频锁定
{$ currentTime | date:'mm:ss' $}
{$ timeLeft | date:'mm:ss' $}
除了正则表达式对象及字面量外,String 对象中也有多个方法支持正则表达式操作,我们 来通过例子讨论这些方法:
方法 | 作用 |
---|---|
match | 匹配正则表达式,返回匹配数组 |
replace | 替换 |
split | 分割 |
search | 查找,返回首次发现的位置 |
var str = "life is very much like a mirror.";
var result = str.match(/is|a/g);
print(result);//返回["is", "a"]
这个例子通过 String 的 match 来匹配 str 对象,得到返回值为[“is”, “a”]的一个数组。
var str = "<span>Welcome, John</span>";
var result = str.replace(/span/g, "div");
print(str);
print(result);
得到结果:
<span>Welcome, John</span>
<div>Welcome, John</div>
也就是说,replace 方法不会影响原始字符串,而将新的串作为返回值。如果我们在替换过 程中,需要对匹配的组进行引用(正如之前的\1,\2 方式那样),需要怎么做呢?还是上边这 个例子,我们要在替换的过程中,将 Welcome 和 John 两个单词调换顺序,编程 John, Welcome:
var result = str.replace(/(\w+),\s(\w+)/g, "$2, $1");
print(result);
可以得到这样的结果:
<span>John, Welcome</span>
因此,我们可以通过$n 来对第 n 个分组进行引用。
var str = "john : tomorrow :remove:file";
var result = str.split(/\s*:\s*/);
print(str);
print(result);
得到结果:
john : tomorrow :remove:file
john,tomorrow,remove,file
注意此处 split 方法的返回值 result 是一个数组。其中包含了 4 个元素。
var str = "Tomorrow is another day";
var index = str.search(/another/);
print(index);//12
search 方法会返回查找到的文本在模式中的位置,如果查找不到,返回-1。
在线练习
{$ activeFileHint $}