javascript 正则 regexp

正则转义字符:
		Table 10-2. Regular expression character classes
Character Matches
[...] Any one character between the brackets.
[^...] Any one character not between the brackets.
. Any character except newline or another Unicode line terminator.
w Any ASCII word character. Equivalent to [a-zA-Z0-9_].
W Any character that is not an ASCII word character. Equivalent to [^a-zA-Z0-9_].
s Any Unicode whitespace character.
S Any character that is not Unicode whitespace. Note that w and S are not the same thing.
d Any ASCII digit. Equivalent to [0-9].
D Any character other than an ASCII digit. Equivalent to [^0-9].
[] A literal backspace (special case).
	匹配次数:
Character Meaning
{ n , m } Match the previous item at least n times but no more than m times.
{ n ,} Match the previous item n or more times.
{ n } Match exactly n occurrences of the previous item.
? Match zero or one occurrences of the previous item. That is, the previous item is optional. Equivalent to {0,1}.
+ Match one or more occurrences of the previous item. Equivalent to {1,}.
* Match zero or more occurrences of the previous item. Equivalent to {0,}.
非贪婪模式:
		在匹配次数后面加个问号'?',尽量按少的次数匹配
var test='aaaca';
console.log(test.replace(/a+/,'b'));     //=>bca    贪婪非全局匹配
console.log(test.replace(/a+?/,'b'));    //=>baaca  非贪婪非全局匹配
console.log(test.replace(/a+/g,'b'));    //=>bcb    贪婪全局匹配
console.log(test.replace(/a+?/g,'b'));   //=>bbbcb  非贪婪全局匹配 ,开启g标志,多次以非贪婪模式匹配
注意:正则匹配尽量找出第一个匹配的位置。因此由于若在首个字符能匹配的情况下,在后来的字符序列进行更短的匹配将不予考虑。
var test='aaaca';
console.log(test.replace(/a+c/,'b'));     //=>ba    贪婪非全局匹配
console.log(test.replace(/a+?c/,'b'));    //=>ba    非贪婪非全局匹配
console.log(test.replace(/a+c/g,'b'));    //=>ba    贪婪全局匹配
console.log(test.replace(/a+?c/g,'b'));   //=>ba    非贪婪全局匹配
间隔,分组,引用
  间隔:| 有点像if elseif,但是如果加了g,就相当于if  if  if
var s='abcdef';
console.log(s.replace(/ab|cd|ef/,'n'));  //单次 只匹配一个  ncdef
console.log(s.replace(/ab|cd|ef/g,'n')); //全局匹配 匹配3个     nnn
  分组:()
	1.将元素用小括号包起来,这样就可以作为一个单元看待,可被用于 |,*,+,?
	2.匹配子模式,并且顺序是按照左边括号的顺序。
		/([Jj]ava([Ss]cript)?)siss(funw*)/ 中 2 引用的是 ([Ss]cript)
		/([Jj]ava(?:[Ss]cript)?)siss(funw*)/   // (?:) 使之不产生引用(即不可回溯),此时 2 引用的是(funw*)
		/['"][^'"]*['"]/    //匹配被带引号的字符串,但是前后可能一个单引号,另一个是双引号
		/(['"])[^'"]*1/    //前后的单引号或者双引号匹配
		/(['"])[^1]*1/    //错误的写法,不能将引用写在分类内部
间隔,分组,引用总结:
Regular expression alternation, grouping, and reference characters
Character Meaning
| 		Alternation. Match either the subexpression to the left or the subexpression to the right.
(...) 		Grouping. Group items into a single unit that can be used with *, +, ?, |, and so on. Also remember the characters
		that match this group for use with later references.
(?:...) 	Grouping only. Group items into a single unit, but do not remember the characters that match this group.仅分组,不可回溯

		Match the same characters that were matched when group number n was first matched. Groups are subexpressions
		within (possibly nested) parentheses. Group numbers are assigned by counting left parentheses from left to right.
	Groups formed with (?: are not numbered.	
特殊的匹配位置:
	 匹配单词边界,即单词(w)与非单词(W)之间的界限,或者是一个字符串的首部或者尾部。【注:在字符分类的中括号[]中,表示回车】
		匹配一个单词:java,其正则为: /java/
		注意:
console.log("abc".match(/abc/));    //[ 'abc', index: 0, input: 'abc' ]  这个表示单词首尾都有单词边界
console.log("abc,".match(/abc,B/));  //[ 'abc,', index: 0, input: 'abc,' ] 这个尾部不是单词边界,因为“,”逗号不属于单词范畴
	B 匹配非单词边界,例如:匹配单词中包含[Ss]cript,但是不是一个独立的script单词: /B[Ss]criptB/
	^  匹配字符串的起始
	$  匹配字符串的结尾
	(?=p)	正向向前断言。要求随后的字符必须匹配p,但是返回的字符不包括p
/[Jj]ava([Ss]cript)?(?=:)/     //匹配“JavaScript: The Definitive Guide”中的“JavaScript”,但是不匹配“Java in a Nutshell”中的“Java”
        
	
	(?!p)	负向向前断言。要求随后的字符必须不匹配p,但是返回的字符不包括p
/Java(?!Script)([A-Z]w*)/     //匹配Java,之后跟一个大写字母,但Java不能直接连着Script。匹配:JavaBeans,JavaSrip。不匹配:                                 Javanese,JavaScript,JavaScripter
var text = '"hello world" javascript';
quote = /"([^"]*)"/g;
console.log(text.match(quote))      // [ '"hello world"' ] 返回值包括双引号
quote = /"([^"]*)(?=")/g;
console.log(text.match(quote));     // [ '"hello world' ]  返回值不包括后面的双引号
var quote = /"([^"]*)(?!")/g;
console.log(text.match(quote));     // [ '"hello worl', '" javascript' ]    匹配项为以双引号开始,不能以双引号结尾,且不包括最后一个非双引号匹配项
标志
		m	多行模式,如果一个字符串中包含换行符,那么启用m标志可匹配到。
var s='Java
is fun';
console.log(s.replace(/java$/im,''));   // => 匹配 Java,输出 is fun
console.log(s.replace(/java$/i,''));    //=>  无匹配项,输出 Java
is fun
	i	Case-insensitive.忽视大小写。
	g	全局匹配,不开启次标志找到一个就不再匹配。若开启,则会找到所有的匹配项,
字符串的正则表达式方法
	1.string.search(regexp): 
				返回匹配的下标,若匹配失败返回-1。
			 	如果传递的参数不是正则,将传递给RegExp创建一个正则对象。
			 	不支持全局匹配。标志g将被忽略。
"JavaScript".search(/script/i);    // => 4    
	2.string.replace(searchRegExp,replaceStr):
				第一个参数可以是字符串也可以是正则。若为字符串,将仅按字符串进行匹配,不会自动转换为正则。
				如果首个参数为正则且包含标志g,将替换所有匹配项,而非第一个匹配项。
				若首个参数有分组,在第二个参数可以用$n进行引用。
var text = '"hello world" javascript';
var quote = /"([^"]*)"/g;
console.log(text.replace(quote, '“$1 lan”'));    //=>“hello world lan” javascript 
	3.string.match(regexp): 	
		返回一个包含匹配结果的数组,若参数为字符串,则将其传递给RegExp构造函数,创建一个RegExp对象。
		此方法对g标志有特殊的行为:
		若开启g标志,返回的数组中是所有的匹配项
"1 plus 2 equals 3".match(/d+/g) // returns ["1", "2", "3"]
		若无g标志,首个元素为匹配字符串,从第二个元素开始按顺序匹配正则表达式中的分组子式。若用replace()来说明则result[1]对应$1,						以此类推。
var url = /(w+)://([w.]+)/(S*)/;
var text = "Visit my blog at http://www.example.com/~david";
var result = text.match(url);
if (result != null) {
    var fullurl = result[0]; // Contains "http://www.example.com/~david"        //匹配结果
    var protocol = result[1]; // Contains "http"                            //分组子式1
    var host = result[2]; // Contains "www.example.com"                    //分组子式2
    var path = result[3]; // Contains "~david"                            //分组子式3
}
 向match方法传递非全局正则没什么意义,就像传递给exec()一样,返回的数组中有下标,还有输入属性。
		
var quote = /"([^"]*)(?!")/;

var text = '"hello world" javascript';
var message = text.match(quote);
console.log(message);     //[""hello worl", "hello worl", index: 0, input: ""hello world" javascript"]
                         //[匹配项,分组子式(?!负向匹配不能回溯,因此不出现在结果里),匹配下标,输入的字符串]
	
  4.string.split(regexp):
      可以接收字符串为参数:"123,456,789".split(","); // Returns ["123","456","789"]
         亦可接收正则式为参数:"1, 2, 3, 4, 5".split(/s*,s*/); // Returns ["1","2","3","4","5"],若split(',')=> [ '1', ' 2', ' 3', ' 4', ' 5' ]
Regexp Object
	由于使用字符串作为参数,因此在字面值正则中的要变为\。
	包含5个属性:
		1.source:只读,包含正则表达式文本
		2.global:只读,标志g
		3.ignoreCase:只读,标志i
		4.multiline:只读,标志m
		5.lastIndex:可读写,开启g标志时,用于匹配下一次开始搜索的位置。
	Regexp对象的方法
	Regexp.exec(str):
		效果和String.match(regexp) 接近。exec()更像match()分解动作。
		不同点在于:
1.	不管标志g是否开启,exec()仅返回一个匹配项,并且提供关于该匹配项完整的信息,比如匹配的位置index和被用于搜索的字符串input [首个元素为匹配字符串,从第二个元素开始按顺序匹配正则表达式中的分组子式。]。
2.	当一个开启g标志的正则调用exec(),其lastIndex将立即被设置为匹配项的后一个位置。同一个正则对象再次调用exec(),将从lastIndex搜索。若找不到匹配项,则lastIndex将被重置为0.	如果使用同一个正则对象去搜索新的字符串,也可以手动设置lastIndex=0.
var pattern = /Java/g;
var text = "JavaScript is more fun than Java!";
for (var result; (result = pattern.exec(text)) != null;) {
    console.log("Matched '" + result[0] + "' at position " + result.index + ";next search begins at " + pattern.lastIndex)
}
// Matched 'Java' at position 0;next search begins at 4 
// Matched 'Java' at position 28;next search begins at 32
  Regexp.test(str):
		 一个简化版的exec(),只是返回true。同时也会改变lastIndex.在正则开启g标志时,下一次将从lastIndex进行搜索。
		字符串方法中,search(),replace(),match()都不会用到lastIndex属性。
var regexp=/java/g;
var s='javascript is not java,it is more funny than java';
while(regexp.test(s))
        console.log('lastINdex: '+regexp.lastIndex)
原文地址:https://www.cnblogs.com/lansor/p/3265040.html