码迷,mamicode.com
首页 > 其他好文 > 详细

5.4 RegExp

时间:2017-12-30 19:10:15      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:ora   模式   new   code   lob   方法   tco   exp   区分   

5.4 RegExp 类型
实例
g全局 i不区分大小写 m多行

var pattern1 = /[bc]at/i

var pattern2 = new RegExp("[bc]at", "i");

5.4.1 RegExp 实例属性(global,ignoreCase, lastIndex, multiline, source
global: 布尔,是否设置了g
ignoreCase 布尔,是否设置了i
lastIndex 整数,匹配的字符位置
multiline 布尔,是否设置了m
source 字符串标识,按照字面量形式返回

var pattern1 = /\[bc\]at/i
l(pattern1.global);//false
l(pattern1.ignoreCase);//true
l(pattern1.multiline);//false
l(pattern1.lastIndex);//0
l(pattern1.source);//\[bc\]at

var pattern1 = new RegExp(‘\\[bc\\]at‘, ‘i‘)
l(pattern1.global);//false
l(pattern1.ignoreCase);//true
l(pattern1.multiline);//false
l(pattern1.lastIndex);//0
l(pattern1.source);//\[bc\]at

5.4.2 RegExp 实例方法(exec(), test()
exec: 接受一个参数,返回应用模式的字符串 index:位置 input:正则表达式字符串
test: 接受一个字符串,匹配返回true,不匹配返回false

var text = ‘mom and dad and baby‘;
var pattern = /mom( and dad( and baby)?)?/gi;
var matches = pattern.exec(text);
l(matches);
l(matches.index);//0
l(matches.input);//mom and dad and baby
l(matches[0]);//mom and dad and baby
l(matches[1]);// and dad and baby
l(matches[2]);// and baby

var text = "cat,bat,sat,fat";
var pattern1 = /.at/;
var matches = pattern1.exec(text);
l(matches.index);//0
l(matches[0]);//cat
l(pattern1.lastIndex);//0

matches = pattern1.exec(text);
l(matches.index);//0
l(matches[0]);//cat
l(pattern1.lastIndex);//0

var pattern2 = /.at/g;
matches = pattern2.exec(text);
l(matches.index);//0
l(matches[0]);//cat
l(pattern2.lastIndex);//3

matches = pattern2.exec(text);
l(matches.index);//4
l(matches[0]);//cat
l(pattern2.lastIndex);//7
var text = "000-00-0000";
var pattern = /\d{3}-\d{2}-\d{4}/;
if(pattern.test(text)){
    l(‘matches‘);//matches
}

var pattern = new RegExp("\\[bc\\]at", "gi");
alert(pattern.toString());///\[bc\]at/gi
alert(pattern.toLocaleString());///\[bc\]at/gi

5.4.3 RegExp 构造函数属性(input,lastMatch,lastParen,leftContext,multiline,rightContext)
input($_):最近一次要匹配的字符串
lastMatch($&): 最近一次匹配项
lastParen($+): 最近一次匹配的捕获组
leftContext($`): input字符串中的lastMatch以前的文本
multiline($*): 布尔值,表示是否所以表达式都使用多行模式
rightContext($‘) input字符串中的lastMatch之后的文本

var text = "this has been a short summer";
var pattern = /(.)hort/g;
if(pattern.test(text)){
    l(RegExp.input);//this has been a short summer
    l(RegExp.leftContext);//this has been a 
    l(RegExp.rightContext);// summer
    l(RegExp.lastMatch);//short
    l(RegExp.lastParen);//s
    l(RegExp.multiline);//false
}

$1,$2,$3

var text = "this has been a short summer";
var pattern = /(..)or(.)/g;
if(pattern.test(text)){
    l(RegExp.$1);//sh
    l(RegExp.$2);//t
}

5.4 RegExp

标签:ora   模式   new   code   lob   方法   tco   exp   区分   

原文地址:https://www.cnblogs.com/caijw/p/8150569.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!