Javascript RegEx quote

前端 未结 3 1836
感情败类
感情败类 2020-12-21 01:28

I\'m having trouble getting this Javascript Regular Expression to work. What i want is to find a character that starts with @\" has any characters in the middle

相关标签:
3条回答
  • 2020-12-21 01:36

    Gumbo's regexp is very nice and all, however it fails to detect escaped quotes (e.g. \", \\\", etc.). A regexp that solves this is as follows:

    /@(["'])[^]*?[^\\](?:\\\\)*\1|@""|@''/g
    

    An explanation (continuing from Gumbo's explanation):

    • [^\\] matches the nearest character preccedding the ending quote that is not a backslash (to anchor the back-slash count check).
    • (?:\\\\)* matches only if the number of backslashes is a multiple of 2 (including zero) so that escaped backslashes are not counted.
    • |@"" checks to see if there is an empty double quote because [^\\] requires at least one character present in the string for it to work.
    • |@'' checks to see if there is an empty single quote.
    0 讨论(0)
  • 2020-12-21 01:37

    The regex would be: var regex = /@"[^"]*"/g;

    0 讨论(0)
  • 2020-12-21 01:43

    Try this regular expression:

    /@(["'])[^]*?\1/g
    

    An explanation:

    • @(["']) matches either @" or @'
    • [^]*? matches any arbitrary character ([^] contains all characters in opposite to . that doesn’t contain line-breaks), but in a non-greedy manner
    • \1 matches the same character as matches with (["'])

    Using the literal RegExp syntax /…/ is more convenient. Note that this doesn’t escape sequences like \" into account.

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