正则表达式基础以及应用

首先是关于正则表达式的基本知识。

一:RegExp(regular expression)对象的创建

RegExp构造函数创建了用于将文本与模式相匹配的正则表达式对象。

有两种方法创建一个正则表达式对象。

(1)文字符号方法

/pattern/attributes

/ab+c/i;

当正则表达式保持不变时使用文字符号方法,例如使用文字符号来构造循环中使用的正则表达式,则每次迭代都不会重新编译正则表达式。

(2)构造函数方法

new RegExp(pattern,modifiers)

new RegExp('ab+c', 'i');

使用这种方式时,正则表达式会在运行时编译,当知道正则表达式模式将会被更改、内容不确定或者可能从其他来源获取,请使用构造函数。

*参数:pattern是一个字符串,指定了正则表达式的模式

modifiers是一个可选的字符串,指定修饰符。

二:RegExp修饰符

"i"-不区分大小写

"g"-全文匹配

"m"-多行匹配

三:RegExp的方法

(1)、RegExp.$1~$9

RegExp.$1是正则表达式的第一个子匹配字符串(以括号为标志)

例:

var re = /(w+)@(w+).(w+)/g //有三个括号,RegExp.$4无

var src = "Please send mail to ptt@yiji.com and zj@yiji.com."

f=re.exec(src);

console.log(RegExp.$1);

console.log(RegExp.$2);

console.log(RegExp.$3);

output:

ptt

yiji

com

(2)、test()

test()是RegExp对象的方法,用来检测字符串是否匹配某个模式,返回true或false。

语法:RegExpObject.test(string) string为要检测的字符串

console.log(/(m+)/.test('mmye'));

output:

true

(3)、exec()

RegExp.exec(str)

exec()方法检索字符串中指定的值并返回该值,若没有发现匹配的值,则返回null。

(4)、compile() --已从web标准中移除

compile()方法用于在脚本执行中编译正则表达式,它与RegExp构造函数基本相同

四:支持正则表达式string对象的方法

(1)、replace()

replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

var str="welcome";

console.log(str.replace("w","m"));

output:

melcome

(2)match()

match()方法用于检索字符串,找到一个数组,当RegExp设置了全局搜索g时,数组长度大于1

(3)search()

str.search(RegExp)

检索与正则表达式想匹配的值,返回第一个与regexp想匹配的子串的位置。

var arr="hello everyone".search(/ev/);

console.log(arr);

output:

6

(4)split()

arr.split(separator,howmany)

split()把字符串分割为字符串数组

var arr="hello everyone";

arr1=arr.split("e");

alert(arr1);

output:

["h", "llo ", "v", "ryon", ""]

五:正则表达式的应用

1、对Date的扩展,将 Date 转化为指定格式的String

// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,

// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)

Date.prototype.Format = function (fmt) {

var o = {

"M+": this.getMonth() + 1, //月

"d+": this.getDate(), //日

"h+": this.getHours(), //小时

"m+": this.getMinutes(), //分

"s+": this.getSeconds(), //秒

"S": this.getMilliseconds() //毫秒

};

// test()检测字符串是否匹配

//(y+) +表示匹配其之前的表达式多次,如y,yy,yyyy

if (/(y+)/.test(fmt)) {

//RegExp.$1是正则表达式匹配的第一个 子匹配(以括号为标志)字符串

fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));

//若年份存在,则被替换成2012-MM-dd

}

// 遍历

for (var k in o){

if (new RegExp("(" + k + ")").test(fmt))

//根据占位符的长度,判断是否需要加在之前加"0"

fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));

}

return fmt;

}

// 调用:

var time2 = new Date("2017/3/25 20:11:11").Format("yyyy-MM-dd hh:mm:ss");

console.log(time2);

</script>

原文地址:https://www.cnblogs.com/weiyemo/p/6690655.html