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
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|\\\\)*'$/ ));
^ tell to the matcher that the next condition must match the begining of the string' will match the ' delimiter( opens a group[^\\'\n\r] matches anything different from \ and ', and will not match the special \n and \r characters| if the condition above didn't match anything, the right side of | will be tested\\' will match \'\\n will match a \n literal string|\\r or will match a \r literal string|\\\\ or will match a \\ literal string)* close the group and allow it to repeat multiple times and allow it to do not exist (empty string for example)' will match the final ' delimiter$ tell to the matcher that this must be the and of the string