Regex适用于浏览器,但不适用于Node.js
我有正则表达式: /(?<!\<)\< [a-zA-Z0-9。 _] + \&/克
。如果我(<<<<< a1>> *< b1> *< c1> *< d1>)*<<< e1>>在浏览器控制台中正常工作.match(/(?<!\<)\< [a-zA-Z0-9。_] + \> / g)
。
I have a regex: /(?<!\<)\<[a-zA-Z0-9. _]+\>/g
. Works fine in browser console if I do "(<<a1>> * <b1> * <c1> * <d1>) * <<e1>>".match(/(?<!\<)\<[a-zA-Z0-9. _]+\>/g)
.
同一行代码抛出 SyntaxError:无效的正则表达式:/(?<!<)<([a-zA-Z0 -9。_] +)> /:在Node.js中执行时无效的组
。
我想匹配我的所有变量包含在<
和>
中的字符串如果被<< 和
>>
。
I want to match all variables in my string enclosed in <
and >
ignore them if enclosed by <<
and >>
.
您可以使用此正则表达式(可能需要稍作更改,具体取决于您是否要检测行的开头/结尾或这些子实体)。我在<>
中的值附近添加了一个caturing组,因为此正则表达式也将匹配< $ c $之前的char c>和
>
之后。
You can use this regex (might need slight changes, depending if you want to detect beginning/end of lines, or these kind of subtilities). I added a caturing group around the value inside the <>
because this regex will also match the char before the <
and after the >
.
如果你的<>
可以放在字符串的开头/结尾:
if your <>
can be placed at beginning/end of string:
/(?:[^<]|^)\<([a-zA-Z0-9. _]+)\>(?:[^<]|$)/g
如果您不需要:
/(?:[^<])\<([a-zA-Z0-9. _]+)\>(?:[^<])/g
注意:不确定这一点,但可能比负面的背后更快。
NOTE: Not sure of this, but might be quicker than a negative lookbehind.
编辑:从您的评论中,我不确定您是否知道捕获群组。它允许你提取你的正则表达式的部分,而不是整个匹配表达式的强制性。
from your comments, i'm not sure you know capturing groups. It allows you to extract parts of your regex, not obligatory the whole matched expression.
要在Javascript中使用它们,请参阅此示例(请注意,您必须删除 /
在正则表达式的开头和结尾,并为正则表达式对象转义 \
:
To use them in Javascript see this example (note that you have to remove the /
at the start and end of the regex and escape the \
too for regex objects):
var myRegex = new RegExp('(?:[^<]|^)\\<([a-zA-Z0-9. _]+)\\>(?:[^<]|$)', 'g'), testStr = '(<<a1>> * <b1> * <c1> * <d1>) * <<e1>>', match, elem = document.getElementById('result');
while (match = myRegex.exec(testStr)) {
elem.innerHTML = elem.innerHTML + match[1] + '<br>';
}
<div id="result"></div>