What is the proper regular expression for an unescaped backslash before a character?

前端 未结 4 864
刺人心
刺人心 2020-12-31 11:18

Let\'s say I want to represent \\q (or any other particular \"backslash-escaped character\"). That is, I want to match \\q but not \\\\q

相关标签:
4条回答
  • 2020-12-31 11:46

    Leon Timmermans got exactly what I was looking for. I would add one small improvement for those who come here later:

    /(?<!\\)(?:\\\\)*\\q/
    

    The additional ?: at the beginning of the (\\\\) group makes it not saved into any match-data. I can't imagine a scenario where I'd want the text of that saved.

    0 讨论(0)
  • 2020-12-31 11:51

    Now You Have Two Problems.

    Just write a simple parser. If the regex ties your head up in knots now, just wait a month.

    0 讨论(0)
  • 2020-12-31 11:57

    The best solution to this is to do your own string parsing as Regular Expressions don't really support what you are trying to do. (rep @Frank Krueger if you go this way, I'm just repeating his advice)

    I did however take a shot at a exclusionary regex. This will match all strings that do not fit your criteria of a "\" followed by a character.

    (?:[\\][\\])(?!(([\\](?![\\])[a-zA-Z])))
    
    0 讨论(0)
  • 2020-12-31 12:02

    Updated: My new and improved Perl regex, supporting more than 3 backslashes:

    /(?<!\\)    # Not preceded by a single backslash
      (?>\\\\)* # an even number of backslashes
      \\q       # Followed by a \q
      /x;

    or if your regex library doesn't support extended syntax.

    /(?<!\\)(?>\\\\)*\\q/

    Output of my test program:

    q does not match
    \q does match
    \\q does not match
    \\\q does match
    \\\\q does not match
    \\\\\q does match

    Older version

    /(?:(?<!\\)|(?<=\\\\))\\q/
    0 讨论(0)
提交回复
热议问题