[removed] negative lookbehind equivalent?

前端 未结 12 1718
南旧
南旧 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:06

    Since 2018, Lookbehind Assertions are part of the ECMAScript language specification.

    // positive lookbehind
    (?<=...)
    // negative lookbehind
    (?

    Answer pre-2018

    As Javascript supports negative lookahead, one way to do it is:

    1. reverse the input string

    2. match with a reversed regex

    3. reverse and reformat the matches


    const reverse = s => s.split('').reverse().join('');
    
    const test = (stringToTests, reversedRegexp) => stringToTests
      .map(reverse)
      .forEach((s,i) => {
        const match = reversedRegexp.test(s);
        console.log(stringToTests[i], match, 'token:', match ? reverse(reversedRegexp.exec(s)[0]) : 'Ø');
      });
    

    Example 1:

    Following @andrew-ensley's question:

    test(['jim', 'm', 'jam'], /m(?!([abcdefg]))/)
    

    Outputs:

    jim true token: m
    m true token: m
    jam false token: Ø
    

    Example 2:

    Following @neaumusic comment (match max-height but not line-height, the token being height):

    test(['max-height', 'line-height'], /thgieh(?!(-enil))/)
    

    Outputs:

    max-height true token: height
    line-height false token: Ø
    

提交回复
热议问题