您的位置:首页 > Web前端 > JavaScript

js正则表达式基本语法

2016-11-08 21:46 274 查看

一、RegExp对象概述

RegExp对象表示正则表达式,RegExp是正则表达式的缩写,它是对字符串执行模式匹配的强大工具。RegExp对象用于规定在文本中检索的内容。当您检索某个文本时,可以使用一种模式来描述要检索的内容。RegExp就是这种模式。简单的模式可以是一个单独的字符;更复杂的模式包括了更多的字符,并可用于解析、格式检查、替换等。

正则表达式可以规定字符串中的检索位置,以及要检索的字符类型等。

二、创建RexExp对象

创建正则表达式和创建字符串类似,创建正则表达式有两种方式:

(1)使用字面量创建RegExp对象的语法:

/pattern/attributes;

(2)使用new关键词创建RegExp对象的语法:

new RegExp(pattern, attributes);

参数释义:

1参数pattern是一个字符串,指定了正则表达式的模式或其他正则表达式。

2参数attributes是一个可选的模式字符串,包含属性 “g”、”i” 和 “m”,分别用于指定全局匹配、不区分大小写的匹配和多行匹配。

RegExp对象用于存储检索模式。通过new关键词来创建RegExp对象。以下代创建了名为pattern的 RegExp对象,其模式是 “e”,当使用该RegExp对象在一个字符串中检索时,将寻找的是字符 “e”。

var pattern=new RegExp("e");
var pattern=new RegExp("e",gi);//设置全局搜素不区分大小


上述的也可以改成字面量的方式来创建,这种方式也是我们经常使用的方法:

var pattern=/e/;
var pattern=/e/gi;


三、RegExp对象详细解析

(1)RegExp对象属性



这些基本我们在上述的例子都已经见过,但我们还是举几个简单的例子来看一下:

var pattern=/e/gim;
document.write(pattern.global+" ");//输出:true。说明设置了全局模式
document.write(pattern.ignoreCase+" ");//输出:true
document.write(pattern.multiline+" ");//输出:true
document.write(pattern.source+" ");//输出:e


(2)RegExp对象方法



RegExp对象有3个方法:test()、exec()以及compile()。

1)test()方法检索字符串中的指定值,返回值是true或false。

var pattern=/e/;
var str="The best things in life are free";
document.write(pattern.test(str));//输出:true


2)exec()方法检索字符串中的指定值,返回值是被找到的值;如果没有发现匹配,则返回null。

var pattern=/e/;
var str="The best things in life are free";
document.write(pattern.exec(str));//输出:e


实例:

向RegExp对象添加第二个参数,以设定检索。如果需要找到所有某个字符的所有存在,则可以使用 “g” 参数。

在使用 “g” 参数时,exec() 的工作原理如下:

1找到第一个 “e”,并存储其位置。

2如果再次运行exec(),则从存储的位置开始检索,并找到下一个 “e”,并存储其位置。

var pattern=/e/g;
var str="The best things in life are free";
do
{
var result=pattern.exec(str);
document.write(result+" ");
}
while(result!=null)


输出的结果为:e e e e e e null

3)compile()方法用于改变正则表达式,compile()既可以改变检索模式,也可以添加或删除第二个参数。

var pattern=/e/;
var str="The best things in life are free";
document.write(pattern.test(str));//输出:true
pattern.compile("d");
document.write(pattern.test(str));//输出:false


(3)支持正则表达式的String对象的方法



由于正则表达式和String对象有着一定的联系,因此String对象的一些方法可用于正则表达式:

var pattern=/e/g;//开启全局模式
var str="The best things in life are free";
document.write(str.match(pattren)+"<br/>");//以数组的形式输出:e,e,e,e,e,e
document.write(str.search(pattren)+"<br/>");//输出:2(返回第一个匹配到的位置)
document.write(str.replace(pattren,"a")+"<br/>");//输出:Tha bast things in lifa ara fraa
var pattern1=/\s/g;//\s表示空格字符
document.write(str.split(pattren1));//输出:The,best,things,in,life,are,free


(4)元字符是拥有特殊含义的字符:



(5)方括号用于查找某个范围的字符:



(6)量词

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息