RegExp对象
直接量匹配
/pattern/attributes
即/表达式/附加属性
创建RegExp对象的语法
new RegExp(pattern,attributes)
$
1.这两个的选取区别:RegExp对象可以调用它所拥有的方法,具体看后面的例子。(其实不用过分纠结区别)
2.如果pattern是一个正则表达式的话,则不可以再添加的写附加属性,否则会抛出异常。
附加属性(修饰符)
i:执行对大小写不敏感的匹配
g:执行全局匹配(并不是在找到了第一个了就停止匹配了,而是找到完为止)
正则表达式的量词元字符等同java的正则表达式
RegExp对象的方法
compile()方法
可以用在改变和重新编译正则表达式。
对象.compile(正则表达,属性)
ex:
在字符串中全局搜索 "man",并用 "person" 替换。然后通过 compile() 方法,改变正则表达式,用 "person" 替换 "man" 或 "woman"
<html>
<body>
<script>
var str="Every man in the world! Every woman on earth!";
var patt=new RegExp("man","g");//can be instead of patt=/man/g;
str2=str.replace(patt,"person");
document.write(str+"</br>");
patt=/(wo)?man/g;
patt.compile(patt);
str2=str.replace(patt,"person");
document.write(str2);
</script>
</body>
</html>
exec()方法
其和string中的match()方法的不同:
在不是全局匹配的时候,它返回的是index和input属性。index属性是匹配文本第一个字符
的位置,即第一个字符出现的第一个位置。而input属性是存放被检索的字符串string。
故这两个一样。返回找到的字符串。(但是可以调用index来查看属性值)
当是全局匹配的时候,exec()找到了匹配文本后,index()是匹配文本的最后一个字符的下一个
位置。故可以通过反复的调用来遍历一个字符串中的所有文本。当exec()找不到匹配的文本的时候,
它将会返回null,并把lastindex属性重新置为0。返回找到的字符串。
$如果在一个字符串中完成了一次模式匹配之后要开始检索新的字符串,就必须
手动将laseIndex属性归0。
还有一个重要的:在循环中反复地调用exec()方法是唯一一种获得全局模式的完整匹配信息的
方法。
ex:
<html>
<body>
<script>
var str="visit csdn,csdn is a good place";
var patt=new RexExp("csdn","g");
var result;
while((result=patt.exec(str))!=null)
{
document.write(result);
document.wirte("</br>");
document.write(patt.lastIndex);
document.write("</br>");
}
</script>
</body>
</html>
test()方法
用于检测一个字符串中是否匹配某个模式。
对象,test(string)
返回true或者false。
等价于r.exec(s)!=null.
ex:
<script>
var str="visit csdn";
var patt=new RegExp("csdn");
var result=patt.test(str);
document.write(result);
</script>
RegExp对象的属性
global 判断对象是否有标志g
ignoreCase 判断对象是否具有标志i
lastIndex 表示下一次开始匹配的字符的位置。
source 正则表达式的文本。
支持正则表达式的String对象的方法
search()
找到要匹配的字符串,如果没有找到则返回-1,找到则返回字符串中与
正则表达式相匹配的字符串的起始位置。
注意:它不支持全局匹配。
ex:
var str="visit csdn";
document.write(str.search(/csdn/);
则返回6.
还有,它对大小写敏感。
如果要忽视大小写,则加上i 属性。
match()
检索字符串,并且返回找到的文本。
ex:
使用正则表达式来匹配所有的数字:
var str="csdn 1 angd 3 andd 5";
document.write(str.match(/\d+/g);
则输出:1,2,3
replace()
ex1:
简单的替换
<script>
var str="hello csdn";
document.write(str.replace(/csdn/,"apple"));
</script>
如果要全局替换,则属性加个g
ex2:
把 "Doe, John" 转换为 "John Doe" 的形式
<script>
name="Doe,"john";
name.replace(/(\w+)\s*,\s*(\w+)/,"$2 $1");
</script>
在这里$1表示第一个子串,$2表示第二个子串。这就和java中的捕获组是一个道理。
ex3:
把所有的花引号替换为直引号:
<script>
name="afsfsf","fsgg";
name.replace(/"([^"]*)"/g,"'$1'");
</script>
ex4:把单词的首字母变成大写
<html>
<body>
<script>
name="adf fsf fdf";
uw=name.replace(/\b\w+\b/g,function(word){
return word.substring(0,1).toUpperCase()+word.substringstring(1)};);
document.write (uw);
</script>
</body>
</html>
解释:关于函数function()
该函数的第一个参数是匹配模式的字符串,之后的参数是其子字符串。
比如在这里,第一个字符串是abf,第二个是fsf,第三个是fdf。