问答 百科手机端

用字符串的match方法检查正则表达式中的子字符串是否存在于原字符串,并返回存在的子字符串

2023-04-12 15:33

正则表达式的test只能检查字符串是否存在,返回true或false,而字符串的match检查是否存在时会返回子字符串。

"Hello, World!".match(/Hello/);
let ourStr = "Regular expressions";
let ourRegex = /expressions/;
ourStr.match(ourRegex);

第一个match返回["Hello"],第二个match返回["expressions"]。.match语法与之前使用的.test方法“相反”:

'string'.match(/regex/);
/regex/.test('string');

再看一个例子:

let extractStr = "Extract the word 'coding' from this string.";
let codingRegex = /coding/; 
let result = extractStr.match(codingRegex);  //注意这儿是字符串.match而不是正则表达式.
console.log(result);
/*控制台输出:
  [ 'coding',
  index: 18,
  input: 'Extract the word \'coding\' from this string.',
  groups: undefined ]*/

如果子字符串在原字符串中多次出现,按上面的办法也只会给出一次:

let testStr = "Repeat, Repeat, Repeat";
let ourRegex = /Repeat/;
let myResult=testStr.match(ourRegex);
console.log(myResult);

/*控制台输出:
  ['Repeat',
  index: 0,
  input: 'Repeat, Repeat, Repeat',
  groups: undefined ]*/

要多次搜索并提取文本形式的话,则要使用全局搜索标志(flag):g。看下面例子:

let testStr = "Repeat, Repeat, Repeat";
let ourRegex = /Repeat/g;
let myResult=testStr.match(ourRegex);
console.log(myResult); //[ 'Repeat', 'Repeat', 'Repeat' ]

看,这样就会全部提取出来。

正则表达式后可以有多个不同的flag(标志):

let twinkleStar = "Twinkle, twinkle, little star";
let starRegex = /Twinkle/ig; //在正则表达式后可以有多个不同的flag(标志),i表示不区分大小写,g表示可多次搜索或提取。
let result = twinkleStar.match(starRegex);  
console.log(result);//[ 'Twinkle', 'twinkle' ]

看,不论大小写、无论几个全部提取出来了。

热门