Regexp(?< = string)给出了无效的组错误? [英] Regexp (?<=string) is giving invalid group error?

查看:116
本文介绍了Regexp(?< = string)给出了无效的组错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个正则表达式来匹配字符串,例如< tag>某些< / tag> ,我希望结果只返回某事没有标签。



我尝试使用:

  string.match(?/(小于= LT;标记>)*(= LT;?\ /标签>)/克); 

但是它给出了一个错误:



SyntaxError:无效的正则表达式:/(?<=<tag>).*?(?=<\/tag>)/:无效的组;



为什么它不起作用?

解决方案

我想你会喜欢这个

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





这很方便,因为 \1 反向引用匹配代码






在这样的文字上使用

  var re = /(?:<(tag)>)((??.:??<\/\1>))+。 ) (?:< \ / \1>)/ g,
str =这是< tag>一些文字< / tag>并且< tag>匹配< / tag>,
匹配;

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

输出

 标记一些文本
标记匹配






Bonus Soda!您只需修改(标签)(标签|奖励|苏打水)让它在这个字符串上工作

 < tag> yay< / tag>并且在< soda> cans< / soda> 
<中甚至< bonus> sodas< / bonus> / pre>




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


I'm trying to create a regular expression to match a string like <tag>something</tag> and I want the result to return only something without the tags.

i tried using:

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

but its giving an error:

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

why is it not working?

解决方案

I think you will like this

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

This is handy because the \1 backreference matches tag pairs


Use it on text like this

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]);
};

Output

tag some text
tag matching


Bonus Soda! You can simply modify (tag) to be (tag|bonus|soda) to have it work on this string

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


Beware If you nest tags, you would have to apply this regexp recursively.

这篇关于Regexp(?&lt; = string)给出了无效的组错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆