正则表达式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.空白字符

\0 匹配null字符

\b 匹配空格字符

~

3.锚字符

^行首匹配

$行尾匹配

\A 只有匹配字符串开始处

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

\B匹配非单词边界

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

\Z匹配字符串结束处或行尾

\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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值