微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

正则的贪婪,前瞻及属性详解

对正则的深入学习

学习正则我们不能光看看几个修饰符就可以了,因为正则还有许多深入的知识,下面我就来为大家扒一扒。。。

正则的三种方法

  • compile 编译正则表达式。

  • exec 检索字符串中指定的值。返回找到的值,并确定其位置。

  • test 检索字符串中指定的值。返回 true 或 false。

.compile()的用法

compile() 方法用于在脚本执行过程中编译正则表达式,也可用于改变和重新编译正则表达式。

语法

RegExpObject.compile(regexp,modifier)
参数详解
regexp    正则表达式。
modifier    规定匹配的类型。"g" 用于全局匹配,"i" 用于区分大小写,"gi" 用于全局区分大小写的匹配。

实例

在字符串中全局搜索 "man",并用 "person" 替换。然后通过 compile() 方法,改变正则表达式,用 "person" 替换 "man" 或 "woman",

var str="Every man in the world! Every woman on earth!";
patt=/man/g;
str2=str.replace(patt,"person");
document.write(str2+"<br />");
patt=/(wo)?man/g;
patt.compile(patt);
str2=str.replace(patt,"person");
document.write(str2);

输出

Every person in the world! Every woperson on earth!
Every person in the world! Every person on earth!

.exec()的用法

exec() 方法用于检索字符串中的正则表达式的匹配。

语法

RegExpObject.exec(string)

参数
string 要检索的值

实例

我们需要找到my,并检索

var str = "hi my name is motor how are you";
var reg = /my/;
reg.exec(str)

输出my

.test()用法

test() 方法用于检测一个字符串是否匹配某个模式.

语法

RegExpObject.test(string)

参数
string 要检索的值

实例

我们需要找到my,并检索

var str = "hi my name is motor how are you";
var reg = /my/;
reg.test(str)

输出true

贪婪

什么是正则表达式的贪婪与非贪婪匹配

  如:String str="abcaxc";
    Patter p="ab*c";

  • 贪婪匹配:正则表达式一般趋向于最大长度匹配,也就是所谓的贪婪匹配。如上面使用模式p匹配字符串str,结果就是匹配到:abcaxc(ab*c)。

  • 非贪婪匹配:就是匹配到结果就好,就少的匹配字符。如上面使用模式p匹配字符串str,结果就是匹配到:abc(ab*c)。

编程中如何区分两种模式

认是贪婪模式;在量词后面直接加上一个问号?就是非贪婪模式。

量词:

{m,n}:m到n个 
*:任意多个
+:一个到多个
?:0或一个

前瞻

正向前瞻

//判断一个单词字符之后是否是数字(正向前瞻),是的话,则符合匹配,进行替换
var str = "a2*3";
var reg = /\w(?=\d)/g;
str.replace(reg,"X");
>>result: 'X2*3'

反向前瞻

//判断一个单词字符之后是否是非数字(负向前瞻),是的话,则符合匹配,进行替换
var str = "a2*3";
var reg = /\w(?!\d)/g;
str.replace(reg,"X");
>>result: 'aX*X'

属性

  • ignoreCase RegExp 对象是否具有标志 i。

  • global RegExp 对象是否具有标志 g。

  • multiline RegExp 对象是否具有标志 m。

  • source 正则表达式的源文本。

  • lastIndex 一个整数,标示开始下一次匹配的字符位置。

source

var reg = /name/;
reg.source

输出name

lastIndex

var str = "hi my name is motor how are you";
    var reg = /m/g;
    console.log(reg.exec(str))
    console.log(reg.lastIndex)
    console.log(reg.exec(str))
    console.log(reg.lastIndex)
    console.log(reg.exec(str))
    console.log(reg.lastIndex)
    console.log(reg.exec(str))
    console.log(reg.lastIndex)
    console.log(reg.exec(str))
    console.log(reg.lastIndex)
    console.log(reg.exec(str))
    console.log(reg.lastIndex)

输出

原文地址:https://www.jb51.cc/regex/358051.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐