Regex

JavaScript:

字符串作用与表达式

方法

描述说明

实例

String.match(regex)

针对字符串应用表达式,如果表达式失败返回null,否则返回匹配

var str=”the 90210 area code”;

var pattern=/[0-9]{5}/;

str.match(pattern);//return 90210

String.search(regex)

如果表达式失败返回-1,否则返回匹配位置。

var str=”the 90210 area code”;

var pattern=/[0-9]{5}/;

str.search(pattern);//return 4

String.replace(regex,

replacement)

用另一个字符串替换匹配

var str=”the 90210 area code”;

var pattern=/[0-9]{5}/;

str.replace(pattern,’----’);

//return the ---- area code

String.split(regex)

根据所示表达式拆分结果

var str=”the 90210 area code”;

var pattern=/[0-9]{5}/;

str.split(pattern);

//return array[“the”,”area code”]

使用Regexp对象

方法                        描述说明                   实例

Regexp.compile(regex,flag)

编译表达式

pattern=/[0-9]{5}/;

pattern.compile(pattern);

Regexp.exec(string)

执行表达式对字符串的匹配,并返回第一个匹配。

var str=”the 90210 area code”;

pattern=”[0-9]{5}”;

pattern.compile(pattern);

var strParts=pattern.exec(str);

//return array[“90210”,4,”the 90210 code area”];

Regexp.test(string)

测试表达式对字符串的匹配,并返回boolean

var str=”the 90210 code area ;

pattern=/[0-9]{5}/;

pattern.test(str);

//return true;

PHP中对字符串应用正则表达式:

方法

描述

实例

preg_grep(regex,array)

对数组应用表达式

$text=array(‘the 90210 area code’,’or the 90211 area code’);

$pattern=’/[0-9]{5}/’;

$match=preg_grep(pattern,$text);

//$match contains

Array(0=>’the 90210 area code’,1=>’or the 90211 area code’)

preg_match_all

(regex,string,matches)

对字符串应用表达式并发现所有匹配

$text=”the  90210 area code ”;

$pattern=’/[0-9]{5}/’;

preg_match_all($pattern,$text,$mathces);

//$matches contains:

Array(0=>array(0=>’90210’));

preg_match

(regex,string,,atches)

对字符创应用表达式并发现第一个匹配

$text=”the  90210 area code ”;

$pattern=’/[0-9]{5}/’;

preg_match_all($pattern,$text,$mathces);

//$matches contains:

Array(0=>’90210’);

preg_replace

(regex,replacement,mixed)

对数组或字符串应用表达式,并用数组或字符串替换

$text=”the 90210 area code”;

$pattern=’/[0-9]{5}/’;

$replace=preg_replace($pattern,’---’,$text);

//$replace contains:

“the --- area code”

preg_split(regex,string)

对字符串应用表达式,并根据所示表达式拆分结果

$text=”the 90210 area code”;

$pattern=’/[0-9]{5}/’;

$strParts=preg_split($pattern,$text);

//$strParts contains:

Array(0=>”the”,1=>”area code”);

原文地址:https://www.cnblogs.com/air5215/p/5380034.html