博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
正则表达式RegExp详解(待续)
阅读量:4316 次
发布时间:2019-06-06

本文共 1821 字,大约阅读时间需要 6 分钟。

  正则表达式(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

你可能感兴趣的文章
WordPress资源站点推荐
查看>>
Python性能鸡汤
查看>>
android Manifest.xml选项
查看>>
Cookie/Session机制具体解释
查看>>
ATMEGA16 IOport相关汇总
查看>>
有意思的cmd命令
查看>>
js正則表達式语法
查看>>
Git学习系列-Git基本概念
查看>>
c#多个程序集使用app.config 的解决办法
查看>>
Linux+Apache+PHP+MySQL服务器环境配置(CentOS篇)
查看>>
Linux下获取本机IP地址的代码
查看>>
(C#)调用Webservice,提示远程服务器返回错误(500)内部服务器错误
查看>>
flex布局
查看>>
python-----python的文件操作
查看>>
java Graphics2d消除锯齿,使字体平滑显示
查看>>
控件中添加的成员变量value和control的区别
查看>>
Spring Boot Docker 实战
查看>>
Div Vertical Menu ver3
查看>>
Git简明操作
查看>>
InnoDB为什么要使用auto_Increment
查看>>