正则表达式RegExp详解(待续)

  正则表达式(Regular Expression)是一种描述字符模式的对象,RegExp 对象表示正则表达式,用来验证用户输入。

一,创建正则表达式

1,采用new运算符 

var bb=new RegExp('参数字符串','可选模式修饰符')

2,字面量法

var bb=/参数字符串/可选模式修饰符;

模式修饰符参数

i 忽略大小写

g 全局匹配

m 多行匹配

二,RegExp相关方法

test()在字符串中查找指定正则表达式,返回true或false

exec()在字符串中查找指定正则表达式,成功返回包含该查找字符串的相关信息数组,执行失败则返回null

var pattern = new RegExp('Box','i'); //创建正则表达式,不区分大小写,等效于var pattern=/Box/i

var str ='this is a box';
document.write(pattern.test(str));//true

document.write(pattern.exec(str));//box

 

 //使用一条语句 document.write(/Box/i.test('this is a box'));

三,字符串的正则表达式方法

1.match(pattern)返回pattern中的子串或null

var pattern = new RegExp('Box','ig');
var str ='this is a box,TAH Is A box too';
document.write(str.match(pattern));//box,box

document.write(str.match(pattern).length);//2

2.replace(pattern,'replacement')用replacement替换pattern

var pattern = new RegExp('Box','ig');
var str ='this is a box,TAH Is A box too';
document.write(str.replace(pattern,'oo'));//this is a oo,TAH Is A oo too

3.search(pattern)返回字符串中pattern开始位置


var pattern = new RegExp('Box','i');
var str ='this is a box,TAH Is A box too';
document.write(str.search(pattern));//10找到就返回,不需要g

split(pattern)返回字符串按指定的pattern拆分的数组

var pattern = new RegExp(' ','i');
var str ='this is a box,TAH Is A box too';
document.write(str.split(pattern));//this,is,a,box,TAH,Is,A,box,too

四,正则表达式元字符

元字符是包含特殊含义的字符,可以控制匹配模式的方式

1.单个字符和数字

. 除换行符以外的任何字符

[a-z0-9]匹配括号中字符集中的任意字符

[^a-z0-9]匹配不在括号中的任意字符

d 匹配数字

D 匹配非数字,同[^1-9]

w匹配字母和数字及_

W匹配非字母和数字及_

2.空白字符

匹配null字符

 匹配空格字符

~

3.锚字符

^行首匹配

$行尾匹配

A 只有匹配字符串开始处

匹配单词边界,词在[]内时无效

B匹配非单词边界

G匹配当前搜索的开始位置

匹配字符串结束处或行尾

z只匹配字符串结尾处

4.重复字符

x? 匹配一个或0个x

x*匹配0个或任意多个x

x+匹配至少一个x

(xyz)+匹配至少一个(xyz)

x{m,n}匹配最少m个,最多n个

5.替代字符

this|where|logo 匹配this或where或logo中任意一个

6.记录字符

(string) 用于反向引用的分组

1或$1 2或$2 3或$3 匹配第n个分组中的内容

原文地址:https://www.cnblogs.com/cumting/p/6790188.html