正则表达式用于首次出现

时间:2018-08-18 05:38:46

标签: javascript regex

我有一个看起来像这样的字符串:

"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:“ \”测试文件\“:\” abc.xml \“,\” test2-file \“:\” abcd.xml \“,\” test3-file \“:\” bcde。 xml \“,\” test-file \“:\” def.xml \“”
     1:“ abc.xml \”,\“ test2-file \”:\“ abcd.xml \”,\“ test3-file \”:\“ bcde.xml \”,\“ test-file \”:\ “ def”

2 个答案:

答案 0 :(得分:0)

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

示例

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

它将用,拆分该字符串并将值存储在数组中。

答案 1 :(得分:0)

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

  • 在同一节点或
  • 相同级别

您应该可以直接使用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}`);
    });
}

相关问题