Regex works on browser but not in Node.js

前端 未结 2 769
误落风尘
误落风尘 2021-01-20 20:09

I have a regex: /(?/g. Works fine in browser console if I do \"(<> * * * <

相关标签:
2条回答
  • 2021-01-20 20:45

    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
    

    If you don't need:

    /(?:[^<])\<([a-zA-Z0-9. _]+)\>(?:[^<])/g
    

    NOTE: Not sure of this, but might be quicker than a negative lookbehind.

    EDIT: 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.

    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>

    0 讨论(0)
  • 2021-01-20 20:45

    As an answer as well (more space):
    Unless node.js uses it's own regex engine and not the JavaScript one, lookbehinds are not supported in JS, thus (?<!) cannot work. To somewhat mimic this feature from other programming languages, have a look at Flagrant Badassery or use additional packages like node-re2 or node-perl-regex.

    As for the differences between Browsers, Chrome does support lookbehinds.

    0 讨论(0)
提交回复
热议问题