如何匹配javascript中已知前缀和后缀包围的子字符串

时间:2013-05-09 22:54:38

标签: javascript regex

给定一个字符串,例如:

  

示例字符串,其中包含要匹配的嵌套字符串。

如何隔离子串,只知道它的前缀和后缀,例如在intendedto match之间?

1 个答案:

答案 0 :(得分:9)

使用non-capturing parentheses的正则表达式,如下所示:

string = 'example string with an intended nested string to match.';
regexp = /(?:intended)(.*)(?:to match)/;
firstMatch = regexp.exec(string)[1]; // " nested string "

问号在正则表达式中有多种用法,括号中的问号冒号(?: 更多正则表达式 )non-capturing parentheses

有关exec(),字符串。match()regular expressions的更多详情,请参阅MDN。