[removed] negative lookbehind equivalent?

前端 未结 12 1521
南旧
南旧 2020-11-21 05:47

Is there a way to achieve the equivalent of a negative lookbehind in javascript regular expressions? I need to match a string that does not start with a specific set of cha

12条回答
  •  日久生厌
    2020-11-21 06:30

    As mentioned before, JavaScript allows lookbehinds now. In older browsers you still need a workaround.

    I bet my head there is no way to find a regex without lookbehind that delivers the result exactly. All you can do is working with groups. Suppose you have a regex (?, where Wanted is the regex you want to match and Before is the regex that counts out what should not precede the match. The best you can do is negate the regex Before and use the regex NotBefore(Wanted). The desired result is the first group $1.

    In your case Before=[abcdefg] which is easy to negate NotBefore=[^abcdefg]. So the regex would be [^abcdefg](m). If you need the position of Wanted, you must group NotBefore too, so that the desired result is the second group.

    If matches of the Before pattern have a fixed length n, that is, if the pattern contains no repetitive tokens, you can avoid negating the Before pattern and use the regular expression (?!Before).{n}(Wanted), but still have to use the first group or use the regular expression (?!Before)(.{n})(Wanted) and use the second group. In this example, the pattern Before actually has a fixed length, namely 1, so use the regex (?![abcdefg]).(m) or (?![abcdefg])(.)(m). If you are interested in all matches, add the g flag, see my code snippet:

    function TestSORegEx() {
      var s = "Donald Trump doesn't like jam, but Homer Simpson does.";
      var reg = /(?![abcdefg])(.{1})(m)/gm;
      var out = "Matches and groups of the regex " + 
                "/(?![abcdefg])(.{1})(m)/gm in \ns = \"" + s + "\"";
      var match = reg.exec(s);
      while(match) {
        var start = match.index + match[1].length;
        out += "\nWhole match: " + match[0] + ", starts at: " + match.index
            +  ". Desired match: " + match[2] + ", starts at: " + start + ".";   
        match = reg.exec(s);
      }
      out += "\nResulting string after statement s.replace(reg, \"$1*$2*\")\n"
             + s.replace(reg, "$1*$2*");
      alert(out);
    }
    

提交回复
热议问题