javascript regex of a javascript string

后端 未结 4 1628
迷失自我
迷失自我 2020-12-04 04:14

I need to match a javascript string, with a regular expression, that is a string enclosed by single quote and can only contain a backslashed single quote.

The exampl

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 04:42

    it's not that hard...

    Also, you need to detect some other possible chars sequences like \n, \r or \\, breaking a line without escaping is not valid in javascript, you must use the \n sequence.

    /^'([^\\'\n\r]|\\'|\\n|\\r|\\\\)*'$/
    

    In execution:

    var sample = ["'abcdefg'", // Valid
                  "'abc\\'defg'", // Valid
                  "'abc\\'de\\'fg'", // Valid
                  "'abc\\'\\r\\nde\\'fg'", // Valid
                  "'abc\\'\r\nde\\'fg'", // Invalid
                  "'abc'def'" // Invalid
                 ];
    for(var i = 0; i < sample.length; i++)
        console.log(sample[i].match( /^'([^\\'\n\r]|\\'|\\n|\\r|\\\\)*'$/ ));
    
    1. ^ tell to the matcher that the next condition must match the begining of the string
    2. ' will match the ' delimiter
    3. ( opens a group
    4. [^\\'\n\r] matches anything different from \ and ', and will not match the special \n and \r characters
    5. | if the condition above didn't match anything, the right side of | will be tested
    6. \\' will match \'
    7. \\n will match a \n literal string
    8. |\\r or will match a \r literal string
    9. |\\\\ or will match a \\ literal string
    10. )* close the group and allow it to repeat multiple times and allow it to do not exist (empty string for example)
    11. ' will match the final ' delimiter
    12. $ tell to the matcher that this must be the and of the string

提交回复
热议问题