简体   繁体   English

以引号开头但不以转义字符开头的字符串的正则表达式

[英]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 (/)如何在javascript中编写一个regex,它只返回一个以双引号开头和结尾的字符串,但不应该有任何转义字符(/)

Don't need a regex here - simple first character check with charAt :这里不需要正则表达式 - 使用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.一个可能的解决方案是使用JSON.parse() ,因为像"hello"这样的字符串也是一个有效的 JSON 对象,而像"hello\\"这样的字符串不是。

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) } });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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