Regex doesn't omit quotes when matching text in quotes

后端 未结 3 624
长发绾君心
长发绾君心 2021-01-24 01:57

I\'m trying to do a non-greedy capture of text inside double quotation marks with regex in node.js. Most of the Google results say I should use one of these:

\"         


        
相关标签:
3条回答
  • 2021-01-24 02:19

    match method returns an array of just matches. See MDN:

    Captured groups are not returned.

    A fix is to use exec:

    var re = /"(.*?)"/g; 
    var str = '|>  "Song" by "Artist" on "Album" <3';
     
    while ((m = re.exec(str)) !== null) {
        document.getElementById("res").innerHTML += m[1] + "<br />";
    }
    <div id="res"/>

    0 讨论(0)
  • 2021-01-24 02:24

    You can give this a shot. This should include everything in the quotes but not the quotes themselves -

    /(?<=")[^" ]*(?=")/ 
    
    0 讨论(0)
  • 2021-01-24 02:35

    Your regex is looking for, and matching quotes. You can do this to modify the value matched to effectively trim off the quotes.

    var testStr = '|>  "Song" by "Artist" on "Album" <3';
    var regex = /"([^"]*)"/g; // or /"(.*?)"/g
    var info = testStr.match(regex).map(function (o) {
      return o.substr(1,o.length-2)
    });
    if (info){
        console.dir(info[0]);
        console.dir(info[1]);
        console.dir(info[2]);
    }
    
    0 讨论(0)
提交回复
热议问题