【问题标题】:Regex: Match a string value in JSON array, split string into multiple values正则表达式:匹配 JSON 数组中的字符串值,将字符串拆分为多个值
【发布时间】:2015-06-15 16:30:28
【问题描述】:

[工具:Sublime Text 3]

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

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

我正在寻找一个 匹配以下 json 中数组内的字符串的正则​​表达式,并拆分这些结果(见 End result):

["Cleric, Ritual Caster, Wizard"]

最终结果:

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

职业列表(不知道对正则表达式是否有帮助):吟游诗人、牧师、德鲁伊、圣骑士、游侠、术士、术士、法师

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

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

【问题讨论】:

  • 您正在运行哪个工具/语言?
  • "class": ["Ritual Caster"] 是绝对的还是"class": [any single entry]
  • 您使用什么编程语言?是 Java 吗?
  • 不要使用正则表达式处理 JSON。
  • 我正在使用 Sublime Text 3,试图替换 json 文件中的数据

标签: arrays regex json string


【解决方案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/

附: “class”通常是计算机语言中的一个特殊词,例如“id”、“var”等等——如果可能,尽量避免使用“class”作为关键字。最好试试“characterClass”、“professional”、...

【讨论】:

  • 嗯,为什么要先替换,\s,然后用逗号分隔,而不是从/,\s/ 开始?关于您对class 的评论,我猜您的意思是使用它作为属性名称,而不是“关键字”,但实际上,在现代浏览器中使用class 作为属性名称是没有问题的。跨度>
  • 感谢您的建议:您是对的 - 正则表达式可以直接用于拆分 - 更新了我的答案
【解决方案2】:

试试这个:

// 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(',')
}

编辑:

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

此解决方案针对数据模型:

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

并把它变成:

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

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

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

在这种情况下,您将不得不进行一些更高级的循环和检查。

【讨论】:

  • 会的。谢谢@NathanTuggy
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-04
  • 2018-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-09
  • 1970-01-01
相关资源
最近更新 更多