Regexp(?< = string)给出了无效的组错误?

时间:2013-08-19 18:36:04

标签: javascript regex

我正在尝试创建一个正则表达式来匹配像<tag>something</tag>这样的字符串,我希望结果只返回something而没有标记。

我尝试使用:

string.match(/(?<=<tag>).*?(?=<\/tag>)/g);

但它给出了一个错误:

SyntaxError:Invalid regular expression: /(?<=<tag>).*?(?=<\/tag>)/: Invalid group;

为什么不起作用?

3 个答案:

答案 0 :(得分:4)

我想你会喜欢这个

/(?:<(tag)>)((?:.(?!<\/\1>))+.)(?:<\/\1>)/g

Regular expression visualization

visualize the match, luke!

这很方便,因为\1 backreference匹配标记


在像这样的文字上使用它

var re  = /(?:<(tag)>)((?:.(?!<\/\1>))+.)(?:<\/\1>)/g,
    str = "this is <tag>some text</tag> and it does <tag>matching</tag>",
    match;

while ((match = re.exec(str)) !== null) {
  console.log(match[1], match[2]);
};

输出

tag some text
tag matching

Bonus Soda!您只需将(tag)修改为(tag|bonus|soda)即可使其适用于此字符串

<tag>yay</tag> and there's even <bonus>sodas</bonus> in <soda>cans</soda>

小心如果嵌套标记,则必须递归应用此正则表达式。

答案 1 :(得分:0)

看起来你正在尝试使用JavaScript不支持的lookbehind。您必须将模式更改为以下内容:

/<tag>(.*?)<\/tag>/g

然后提取适当的组。例如:

/<tag>(.*?)<\/tag>/g.exec('<tag>something</tag>')[1]; // something

答案 2 :(得分:0)

试试这个:

var result = /<tag>(.*?)<\/tag>/.exec(myString,"g");

之间的文字是结果[1]。

相关问题