segment 2009-03-27
正则表达式学习:
1.定义RegExp:
var patt1=new RegExp("e");
2. RegExp对象有三个方法:test(),exec()以及compile()。
test() 方法检索字符串中的指定值。返回值是 true 或 false。
document.write(patt1.test("The best things in life are free"));
exec() 方法检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配,则返回 null。
document.write(patt1.exec("The best things in life are free"));
compile() 既可以改变检索模式,也可以添加或删除第二个参数。
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
patt1.compile("d");
document.write(patt1.test("The best things in life are free"));
输出true和false;
search() 方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。 返回stringObject 中第一个与 regexp 相匹配的子串的起始位置。
search对大小写敏感,如果找不到则返回-1;
match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。该方法类似 indexOf() 和 lastIndexOf(),但是它返回指定的值,而不是字符串的位置。
replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。
/一次替换;
<script type="text/javascript">
var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/, "W3School"))
</script>
/全局替换;
<script type="text/javascript">
var str="Welcome to Microsoft! "
str=str + "We are proud to announce that Microsoft has "
str=str + "one of the largest Web Developers sites in the world."
document.write(str.replace(/Microsoft/g, "W3School"))
</script>
split() 方法用于把一个字符串分割成字符串数组。
\d 匹配数字
\w 任意字母或数字或下划线
\s 还包括空格,制表符,换页符等空白字符;
. 除了换行符\n以外的任意字符;
[] 包含一系列字符,能够匹配其中任意一个字符;
[^] 包含字符之外的任意一个字符;
[f-k] f-k之间的任意一个字符;
[^a-f0-3] a-f0-3之外的任意一个字符;
{n} 重复n次,\w{2}相当于\w\w;
{m,n} 至少重复m次,最多重复n次;
{m,} 至少重复m次;
? 匹配0次或者1次;
+ 至少出现1次;
* 不出现或者出现任意次;
^ 从开始的地方匹配,
$ 结束的地方匹配
\b 单词与空格之间的位置