简体   繁体   中英

Regex for string starting with quote but not with escape character

I have to find a string which start and end with double quotes and then change its color. But if there is escape character (/) with quote then it will not be considered as string and color will not be changed.

For example:

  1. "hello"
  2. \\"hello\\"

The first example will be considered as string while the second example will not be considered as a string.

How to write a regex in javascript which only returns a string which starts and ends with double quotes but there should not have any escape character (/)

Don't need a regex here - simple first character check with charAt :

 const strings = [`"hello"`, `\\\\"hello\\\\"`]; strings.forEach(s => console.log(s.charAt(0) == `"`));

If you really need a regex:

 const strings = [`"hello"`, `\\\\"hello\\\\"`]; const regex = /^[\\"]/; strings.forEach(s => console.log(regex.test(s)));

A possible solution would be using JSON.parse() , since a string like "hello" is also a valid JSON object, while a string like "hello\\" is not.

function checkString(str){
    try {
        // let's try to parse the string as a JSON object
        const parsed = JSON.parse(str);
        // check if the result is a valid javascript string
        return (parsed === String(parsed));
    }
    catch(error){
        return false;
    }
}

EDIT:

If you have an array of objects, and you need to find which object is a valid string, you can do this:

const strings = ['"valid string"', '"not valid string\\"'];
const validStrings = strings.filter((e) => {
    return (e === String(e) && checkString(e));
});

You can use this pattern

^(?!.*\/)".*"$
  • ^ - start of string
  • (?!.*\\\\) - condition to avoid any \\
  • " - Matches "
  • .* - Matches anything except new line
  • $ - End of string

 const strings = [`"hello"`, `\\\\"hello\\\\"`, `\\\\"hello`, `hello"\\\\`, `"hel/lo"`,]; strings.forEach(s => { if(/^(?!.*\\\\)".*"$/.test(s)){ console.log(s) } });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM