簡體   English   中英

以引號開頭但不以轉義字符開頭的字符串的正則表達式

[英]Regex for string starting with quote but not with escape character

我必須找到一個以雙引號開頭和結尾的字符串,然后更改其顏色。 但是如果有帶引號的轉義字符(/),那么它不會被視為字符串並且顏色不會改變。

例如:

  1. “你好”
  2. \\“你好\\”

第一個示例將被視為字符串,而第二個示例將不被視為字符串。

如何在javascript中編寫一個regex,它只返回一個以雙引號開頭和結尾的字符串,但不應該有任何轉義字符(/)

這里不需要正則表達式 - 使用charAt簡單的第一個字符檢查:

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

如果你真的需要一個正則表達式:

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

一個可能的解決方案是使用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;
    }
}

編輯:

如果您有一個對象數組,並且需要查找哪個對象是有效字符串,則可以執行以下操作:

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

你可以使用這個模式

^(?!.*\/)".*"$
  • ^ - 字符串的開始
  • (?!.*\\\\) - 避免任何\\條件
  • " - 匹配"
  • .* - 匹配除新行以外的任何內容
  • $ - 字符串結束

 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