1、找出英文句子中相同的单词(不区分大小写)
var str = "Is is the cost of of gasoline going up up";
var patt1 = /\b([a-z]+) \1\b/ig;
document.write(str.match(patt1)); // Is is,of of,up up
2、找出英文句子中相同的单词(区分大小写)
var str = "Is is the cost of of gasoline going up up";
var patt1 = /\b([a-z]+) \1\b/g;
document.write(str.match(patt1)); // of of,up up
正则表达式解释:
- 捕获的表达式,正如 [a-z]+ 指定的,包括一个或多个字母。
- 正则表达式的第二部分是对以前捕获的子匹配项的引用,即,单词的第二个匹配项正好由括号表达式匹配。\1 指定第一个子匹配项。
- 单词边界元字符 \b 确保只检测整个单词。否则,诸如 "is issued" 或 "this is" 之类的词组将不能正确地被此表达式识别。
- 正则表达式后面的全局标记 g 指定将该表达式应用到输入字符串中能够查找到的尽可能多的匹配。
- 表达式的结尾处的不区分大小写 i 标记指定不区分大小写。