regex to find a string that comes after =

前端 未结 6 1225
萌比男神i
萌比男神i 2021-01-28 07:15

I´m really new to regex and I have been looking around to find an answer but either it dont work or I get some kind of error so I will try to ask the question and hopefulyl some

相关标签:
6条回答
  • 2021-01-28 07:43

    I think this should work :

    ([^[]+)(?:\[[^=]+=([^\]]+)\])+
    

    Explainations :

    ([^[]) First, you match everything that is not a [.

    (?:...)+ Then, when you find it, you're starting repeting a pattern

    \[[^=] Find everything that is not an =, and discard it.

    ([^\]]) Find everything that is not a ] and capture it.

    0 讨论(0)
  • 2021-01-28 07:52

    You can use this regex:

    ([^\[]*)\[[^=]+=([^\]]*)\]\[[^=]+=([^\]]*)\]
    

    You can then grap matching group #1, #2 and #3

    Live Demo: http://www.rubular.com/r/XNZfHcMAp8

    In Javascript:

    str = 'car[brand=saab][wheels=4]';
    console.log('match::' + str.match(/([^[]*)\[[^=]+=([^\]]*)\]\[[^=]+=([^\]]*)\]/));
    
    0 讨论(0)
  • 2021-01-28 07:54
    /([^\[]+)\[brand=([^\]]+)\]\[wheels=(\d)\]/
    

    Works.

    Try it like

    var result = "car[brand=saab][wheels=4]".match(/([^\[]+)\[brand=([^\]]+)\]\[wheels=(\d)\]/)
    

    Result would be

    [ "car[brand=saab][wheels=4]", "car", "saab", "4" ]
    
    0 讨论(0)
  • 2021-01-28 08:03

    .replace with a callback function is your tool of choice when parsing custom formats in javascript. Consider:

    parse = function(s) {
        var result = {};
        s.replace(/^(\w+)|\[(.+?)=(.+?)\]/g, function($0, $1, $2, $3) {
            result[$2 || "kind"] = $1 || $3;
        });
        return result;
    }
    

    Example:

    str = "car[brand=saab][wheels=4][price=1234][morestuff=foobar]"
    console.log(parse(str))
    // {"kind":"car","brand":"saab","wheels":"4","price":"1234","morestuff":"foobar"}
    
    0 讨论(0)
  • 2021-01-28 08:03

    you could do it with match in one shot, and get an array back.

    below lines were tested in chrome console:

    str = "car[brand=saab][wheels=4]";
    "car[brand=saab][wheels=4]"
    str.match(/[^=[\]]+(?=[[\]])/g)
    ["car", "saab", "4"]
    
    0 讨论(0)
  • 2021-01-28 08:07
    function getObject(str) {
    
        var props = str.split(/\[(.*?)\]/g),
            object = {};
        if (props.length) {
            object.name = props.shift();
            while (props.length) {
                var prop = props.shift().split("=");
                if(prop.length == 2){
                    object[prop[0]] = prop[1];
                }
            }
        }
        return object;
    }
    
    console.log(getObject("car[brand=saab][wheels=4]"));
    
    0 讨论(0)
提交回复
热议问题