regex between two special characters

后端 未结 6 1175
花落未央
花落未央 2021-01-26 11:12

Is there a way to replicate this PHP snippet in JQuery or Javascript...



        
相关标签:
6条回答
  • 2021-01-26 11:21

    Is this what you need?

    var value = "some {example}";
    value.match(/{([^}]+)}/); //array[0] = "{example}" --- array[1] = "example"
    
    0 讨论(0)
  • 2021-01-26 11:28

    Regex are pretty much the same across all languages. If you want to get everything in between {} and put it into an array you can do this:

    var arr = [];
    var str = 'Lorem {ipsum dolor} sit {amet} conseteur {adipisci}';
    str.replace(/{(.+?)}/g, function(a, b){ arr.push(b) });
    
    console.log(arr); //=> ["ipsum dolor", "amet", "adipisci"]
    

    Demo: http://jsfiddle.net/elclanrs/xeHZn/

    0 讨论(0)
  • 2021-01-26 11:28

    This expression should work fine:

    /{([^}]+)}/g
    
    0 讨论(0)
  • 2021-01-26 11:33
    var str = '{Some groovy text}not so groovy text';
    var regex = /\{(.*?)\}/;
    var value = str.match(regex)[1];  // 'Some groovy text';
    

    This will retrieve the content within the brackets. Hope this helps.

    0 讨论(0)
  • 2021-01-26 11:35

    Something like this should do:

     var re = /{[^}]*}/g;
     var s = '{foo},bar,{fum}';
    
     alert(s.match(re)); // ['{foo}','{fum}']
    

    but you may not want the "{}" included.

    var re = /{([^}]*)}/g;
    var s = '{foo},bar,{fum}';
    
    var a = [];
    var b;
    while (b = re.exec(s)) {
      a.push(b[1]);
    }
    
    alert(a); // ['foo','fum'];
    

    There's bound to be a way to do it with a single regular expression and no loop.

    0 讨论(0)
  • 2021-01-26 11:45

    You can get all blocks of text between { and } into an array with this:

    function getBracedText(input) {
        var re = /\{(.*?)\}/g, matches, output = [];
        while (matches = re.exec(input)) {
            output.push(matches[1]);
        }
        return(output);
    }
    
    var str = "Some text {tag} and more {text}";
    var results = getBracedText(str);
    // results == ["tag", "text"];
    

    Working demo: http://jsfiddle.net/jfriend00/DT4Km/

    0 讨论(0)
提交回复
热议问题