匹配h的六级标签
// 如果不使用回溯引用,是无法得到标签开头的
(/<([hH][1-6])>.*?<\/[hH][1-6]/g).test("<h1>asd</h2>"); // true
//使用回溯引用,可以得到正确的匹配
(/<([hH][1-6])>.*?<\/\1/g).test("<h1>asd</h2>"); // false
(/<([hH][1-6])>.*?<\/\1/g).test("<h1>asd</h1>"); // true
//[" of of", " and and"]
"this is a block of of text several words here and repeated, and and they should not be.".match(/\s+(\w+)\s+\1/g);
回溯查找在替换操作中有很大作用。
//"(010)-1234567"
"010-123-4567".replace(/(\d{3})(-)(\d{3})(-)(\d{4})/,"($1)$2$3$5");
注意:javascript中用$n表示引用第n个子表达式。
有些正则表达式允许在替换中队大小写进行替换:
元字符 | 说明 |
---|---|
\E | 结束\L或者\U转换 |
\l | 把下一个字符转换为小写 |
\L | 把\L和\E之间的字符全部转换为小写 |
\u | 把下一个字符转换为大写 |
\U | 把\U和\E之间的字符全部转换为大写 |
JavaScript无效