标签:java art io cti javascript re
创建正则表达式
var pat1 = /[abc]/i; //方法一
var pat2 = new RegExp("[abc]","i"); //方法二
//匹配第一个"[abc]",不区分大小写
var p1 = new RegExp("[abc]","i"); /[abc]/i
//匹配第一个"a"或"b"或"c",不区分大小写
var p2 = new RegExp("\\[abc\\]",i); /\[abc]/i
// 若是动态字符串,则方法一需要以下方式定义
var p3 = eval("/\\["+str+"\\]/");
"abc".match(p1) => ["a"]
"[abc]".match(p1) => ["a"]
"abc".match(p2) => null
"[abc]".match(p2) => ["[abc]"]
p1.exec("abc")
match与exec同样用法,只是位置相反
RegExp方法:exec() test() compile()
string对象方法:match() search() replace() split()
?(0或1)
*(0或多个)
+(1或多个)
各方法应用
compile()
改变和重新编译正则表达式
例:在字符串中全局搜索 "man",并用 "person" 替换。
然后通过 compile() 方法,改变正则表达式,
用 "person" 替换 "man" 或 "woman"
<script type="text/javascript" >
var str="Every man in the world!Every woman on earth";
patt = /man/g;
str2 = str.replace(patt,"person");
patt = /(wo)?man/g;
patt.compile(patt);
str3 = str.replace(patt,"person");
</script>
exec()
检索字符串,找到匹配项,返回一个数组;没找到,返回null
<script type="text/javascript" >
var str = "visit school";
var patt = /school/g;
var result = patt.exec(str);
while(result != null){
console.log(patt.lastIndex);
}
</script>
test()
检索字符串,找到返回true,找不到返回false
<script type="text/javascript" >
var str = "visit school";
var patt = /school/g;
var result = patt.test(str);
</script>
search()
检索子字符串
<script type="text/javascript" >
var str = "visit school";
var patt = /school/i;
var result = str.search(patt); //6
</script>
match()
<script type="text/javascript" >
var str = "1 plus 2 equal 3";
var result = str.match(/\d+/g); //["1","2","3"]
</script>
replace()
(1)我们将把 "Doe, John" 转换为 "John Doe" 的形式:
name = "Doe, John";
name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1");
(2)匹配所有字符为大写
text = "javascript Tutorial";
text.replace(/javascript/i, "JavaScript");
(3)首字母转大写
name = ‘aaa bbb ccc‘;
uw=name.replace(/\b\w+\b/g, function(word){
return word.substring(0,1).toUpperCase()+word.substring(1);}
);
split()
(1)按照不同方式分割
var str="How are you doing today?"
var a=str.split(""); =>H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?
var b =str.split(" "); =>How,are,you,doing,today?
var c =str.split(" ",3); =>How,are,you
"we are friends".split(/\s+/) => ["we", "are", "firends"]
RegExp实例属性
var p = /abc/g;
标签:java art io cti javascript re
原文地址:http://www.cnblogs.com/teemogao/p/3844657.html