RegExp to get text in a key value pair separated by a colon

前端 未结 3 1608
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 04:36

I have my Regexp example here: https://regex101.com/r/kE9mZ7/1

For the following string:

key_1: some text, maybe a comma, ending in a semicolon; key_2: text

相关标签:
3条回答
  • 2021-01-14 05:16

    This regex should to the trick for you:

    /(\w+):([^;]*)/g
    

    Example here

    0 讨论(0)
  • 2021-01-14 05:17

    Here is a regex way to extract those values:

    /(\w+):\s*([^;]*)/gi
    

    or (as identifiers should begin with _ or a letter):

    /([_a-z]\w*):\s*([^;]*)/gi
    

    Here is a regex demo

    var re = /([_a-z]\w*):\s*([^;]*)/gi; 
    var str = 'key_1: some text, maybe a comma, ending in a semicolon; key_2: text with no ending semicolon';
    while ((m = re.exec(str)) !== null) {
        document.body.innerHTML += m[1] + ": " + m[2] + "<br/>";
    }

    Pattern details:

    • ([_a-z]\w*) - Group 1 matching an identifier starting with _ or a letter and followed with 0+ alphanumeric/underscore symbols
    • : - a colon
    • \s* - 0+ whitespaces
    • ([^;]*) - 0+ characters other than ;. The use of a negated character class eliminates the need of using lazy dot matching with (?:$|;) group after it. NOTE that * quantifier makes the value optional. If it is required, use +.
    0 讨论(0)
  • 2021-01-14 05:32

    You need to add a g modifier, DEMO

    If regex is not mandatory then try

    var input = "key_1: some text, maybe a comma, ending in a semicolon; key_2: text with no ending semicolon";
    var keyValues = input.split(";");
    keyValues.forEach( function(val){
      var keyValue = val.split( ":" );
      alert( "precolon " + keyValue[0] );
      alert( "postcolon " + keyValue[1] );
    });
    
    0 讨论(0)
提交回复
热议问题