javascript regex to select quoted string but not escape quotes

前端 未结 4 721
南旧
南旧 2021-01-19 05:06

Original string:

some text \"some \\\"string\\\"right here \"

Want to get:

\"some \\\"string\\\"right here\"
4条回答
  •  孤独总比滥情好
    2021-01-19 05:52

    Safe regex approach

    Complementing @WiktorStribiżew's answer, there is a technique to start matching at the correct double quote using regex. It consists of matching both quoted and unquoted text in the form:

    /"(quoted)"|unquoted/g
    

    As you can see, the quoted text is matched by a group, so we'll only consider text backreferenced by match[1].

    Regex

    /"([^"\\]*(?:\\.[^"\\]*)*)"|[^"\\]*(?:\\.[^"\\]*)*/g
    

    Code

    var regex = /"([^"\\]*(?:\\.[^"\\]*)*)"|[^"\\]*(?:\\.[^"\\]*)*/g;
    var s = "some text \\\"extras\" some \\\"string \\\" right\" here \"";
    var match;
    var res = [];
    
    while ((match = regex.exec(s)) !== null) {
        if (match.index === regex.lastIndex)
            regex.lastIndex++;
    
        if( match[1] != null )
            res.push(match[1]); //Append to result only group 1
    }
    
    console.log("Correct results (regex technique): ",res)

提交回复
热议问题