正则表达式:匹配JSON数组中的字符串值,将字符串拆分为多个值

时间:2015-06-15 16:30:28

标签: arrays regex json string

[工具:Sublime Text 3]

您好我正在寻找有关正则表达式的帮助,我对它的经验很少,所以我希望得到一些帮助。

我计划使用正则表达式来帮助我用其中的大量数据替换我的json文件(超过6k LOC)。

我正在寻找匹配以下json中数组中的字符串的正则表达式,并拆分这些结果(在结果中看到):< / p>

["Cleric, Ritual Caster, Wizard"]

最终结果:

["Cleric", "Ritual Caster", "Wizard"]

课程列表(不知道它是否有助于正则表达式): Bard,Cleric,Druid,Paladin,Ranger,Sorcerer,Warlock,Wizard

*编辑:我忘记使用Sublime Text 3 atm添加我正在使用的工具,但我可以使用JavaScript在我当前的json文件上重写新数据和copypasta。

删除了无效的json,我只是想编辑/修复数组。

2 个答案:

答案 0 :(得分:1)

试试这个:

// Check the first string in the class property (which is assumedly an array) for a comma.
if (characterStats['class'][0].indexOf(',')) {
    // Reassign the property to the result of splitting this string at every comma. If the array has anything beyond the 0th entry, this will remove it.
    characterStats['class'] = yourBlob['class'][0].split(',')
}

编辑:

所以我们检查数组中的第一个条目,在你的例子中是一个带有多个逗号的大字符串。我们正在检查索引是否为逗号。如果字符串中存在逗号(并且超过第0个索引),那么我们将把对象的.class属性重新分配给在每个逗号处新分割成数组的字符串。

此解决方案解决了数据模型:

{
    class: ['one,big,string,of,words']
}

并将其变为:

{
    class: ['one','big','string','of','words']
}

此解决方案假设您永远不会有这样的事情:

{
    class: ['wizard', 'sorcerer, cleric, knave']
}

在这种情况下,你必须做一些更高级的循环和检查。

答案 1 :(得分:1)

在JS中你可以做到:

var classInput = ["Cleric, Ritual Caster, Wizard"];
var classString = classInput[0];  // get the String from the Array
var classOutput = classString.split(/,\s/g); // split into and Array with separate strings

或更短:

var classInput = ["Cleric, Ritual Caster, Wizard"];
var classOutput = classInput[0].split(/,\s/g);

您的班级列表示例: http://jsfiddle.net/bbmh1a5v/4/

P.S。 “class”通常是计算机语言中的一个特殊单词,如“id”,“var”等等 - 如果可能的话,尽量避免使用“class”作为关键词。最好尝试“characterClass”,“职业”,......