简体   繁体   中英

Regex to get extract parts from String with specific separator, JavaScript

I have example string:

[:pl]Field_value_in_PL[:en]Field_value_in_EN[:]

And I want get something like it:

Object {
    pl: "Field_value_in_PL",
    en: "Field_value_in_EN"
}

But I cannot assume there will be always "[:pl]" and "[:en]" in input string. There can by only :pl or :en, :de and :fr or any other combination.

I tried to write Regexp for this but I failed.

Try using .match() with RegExp /:(\\w{2})/g to match : followed by two alphanumeric characters, .map() to iterate results returned from .match() , String.prototype.slice() to remove : from results, .split() with RegExp /\\[:\\w{2}\\]|\\[:\\]|:\\w{2}/ to remove [ , ] characters and matched : followed by two alphanumeric characters, .filter() with Boolean as parameter to remove empty string from array returned by .split() , use index of .map() to set value of object, return object

 var str = "[:pl]Field_value_in_PL[:en]Field_value_in_EN[:]:deField_value_in_DE"; var props = str.match(/:(\\w{2})/g).map(function(val, index) { var obj = {} , prop = val.slice(1) ,vals = str.split(/\\[:\\w{2}\\]|\\[:\\]|:\\w{2}/).filter(Boolean); obj[prop] = vals[index]; return obj }); console.log(JSON.stringify(props, null, 2)) 

Solution with String.replace , String.split and Array.forEach functions:

var str = "[:pl]Field_value_in_PL[:en]Field_value_in_EN[:fr]Field_value_in_FR[:de]Field_value_in_DE[:]",
    obj = {},
    fragment = "";

var matches = str.replace(/\[:(\w+?)\]([a-zA-Z_]+)/gi, "$1/$2|").split('|');
matches.forEach(function(v){    // iterating through key/value pairs
    fragment = v.split("/");
    if (fragment.length == 2) obj[fragment[0]] = fragment[1];  // making sure that we have a proper 'final' key/value pair
});

console.log(obj);
// the output:
Object { pl: "Field_value_in_PL", en: "Field_value_in_EN", fr: "Field_value_in_FR", de: "Field_value_in_DE" }

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

您可以尝试使用此正则表达式来捕获一组括号内的内容,而另一组捕获括号内的一组单词。

(\\[.*?\\])(\\w+)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM