【问题标题】:Regex for getting first unique occurence用于获取第一个唯一事件的正则表达式
【发布时间】:2018-08-19 03:38:38
【问题描述】:

我的字符串看起来像:

"test-file" : "abc.xml","test2-file":"abcd.xml","test3-file":"bcde.xml","test-file" : "def.xml"'

如何创建一个输出数组的正则表达式:

{abc.xml, def.xml} or {"test-file" : "abc.xml","test-file" : "def.xml"} 

那只是在 ‍‍':' 之前与测试文件配对。

我试过了:

json.match(/"test-file" : "(.*)\.xml"/); 

但我得到了输出:

0: "\"test-file\" : \"abc.xml\",\"test2-file\":\"abcd.xml\",\"test3-file\":\"bcde. xml\",\"测试文件\" : \"def.xml\""
​​​ 1: "abc.xml\",\"test2-file\":\"abcd.xml\",\"test3-file\":\"bcde.xml\",\"test-file\":\ “定义”

【问题讨论】:

  • {abc.xml, def.xml} 这是一个无效的对象。 or {"test-file" : "abc.xml","test-file" : "def.xml"} 这将导致只有一个键值对。
  • @CertainPerformance 感谢您的更正,但是这种问题是否有可能的正则表达式?
  • @wp78de 这个 json 子树可能是带有可变键的更大 json 的一部分,所以不要调用 '.values;反复(因为 json 结构未知),我想将 json 转换为字符串并使用正则表达式查找特定的键值对。有可能吗?
  • 要得到你想要的结果,请.*reluctant:"test-file" : "(.*?\.xml)

标签: javascript regex


【解决方案1】:

如果您要查找的所有键值对都是

  • 在同一节点上或
  • 同级

直接使用 JSON 应该没问题。

我怀疑当您必须处理变量键名时,正则表达式是否会有所帮助。必须有一个标准可以让您区分好密钥和坏密钥。

如果此标准是顺序,这里有一个围绕 Object.keys 构建的示例,用于在不知道键的实际名称的情况下访问值。但是,还有很多其他方法可以做到this

// Function to get the nth key from the object
Object.prototype.getByIndex = function(index) {
  return this[Object.keys(this)[index]];
};

var json = {
    "config": {
        "files": [{
            "name1": "test.xml"},
        {
            "name2": "test2.xml"
        }]
    }
};
$.each(json.config.files, function(i, v) {
    if (i !== 0) // or whatever is a "good" index
        return;
    //or if it is the content of the value the identifies a good value...
    if (v.getByIndex(0).indexOf(".xml") !== -1) {
        console.log(v);
        return;
    }    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

如果您执行大量此类 JSON 查询操作,那么像 JSONiqJSPathjsonpath 这样的 JSON 查询语言/库可能适合您。


如果您的子字符串/键始终相同,您确实可以使用正则表达式,例如

const regex = /"test-file"\s*:\s*".*?\.xml"/g;
const str = `"test-file" : "abc.xml","test2-file":"abcd.xml","test3-file":"bcde.xml","test-file" : "def.xml"'`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

【讨论】:

  • 感谢您的回复,我认为这个解决方案很好,但问题是 Json 派生自一个在不同请求期间可能会有所不同的模式,而不是为那些可能非常大的模式硬编码编号,我对始终相同的子字符串感兴趣,例如“test-file”:“abc.xml”。在一种情况下,它可以有 1 个父级,而在另一种情况下,它可以有多个父级,因此 json 解析并不困难。
【解决方案2】:

将值存储在字符串中并使用拆分功能

示例

test_string='"test-file" : "abc.xml","test2-file":"abcd.xml","test3-file":"bcde.xml","test-file" : "def.xml"';
test_string.split(",");

它会将该字符串拆分为,,并将值存储在一个数组中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多