简体   繁体   English

在JavaScript中使用正则表达式从字符串中提取键值

[英]Extract key value from string with regex in JavaScript

I need a function to extract key values from an string like this: <!-- Name:Peter Smith --><!-- Age:23 --> 我需要一个从这样的字符串中提取键值的函数: <!-名称:Peter Smith-> <!-年龄:23​​->

I want to make an standard function to extract any value. 我想做一个标准函数来提取任何值。 The call is something like this: var name=ExtractValue(text,"Name"); 调用是这样的: var name = ExtractValue(text,“ Name”);

This is my approach: 这是我的方法:

var text="<!-- Name:Peter Smith --><!-- Age:23 -->"; // Data to be scanned

var name=ExtractValue(text,"Name"); // Get the "Name" key value
var age=ExtractValue(text,"Age");   // Get the "Age" key value
document.getElementById("result").innerHTML = "Extracted name: ("+name+"), age: ("+age+")";

// Function for extranting key values
function ExtractValue(data,key){
    // It's try to be like /Name:(.*)\s--/
    var rx = "/"+key+"(.*)\s--/";
    var values = rx.exec(data);
    if(values.lenght>0){
        return values[1];
    } else{
        return "";
    }
}

How can I do this? 我怎样才能做到这一点? Thanks for your time! 谢谢你的时间!

You can do it like this: 您可以这样做:

 var text="<!-- Name:Peter Smith --><!-- Age:23 -->"; // Data to be scanned var name=ExtractValue(text,"Name"); // Get the "Name" key value var age=ExtractValue(text,"Age"); // Get the "Age" key value console.log("Extracted name: ("+name+"), age: ("+age+")"); function ExtractValue(data,key){ var rx = new RegExp(key + ":(.*?)\\\\s+--"); var values = rx.exec(data); // or: data.match(rx); return values && values[1]; } 

Don't forget to escape backslashes in a string literal. 不要忘记在字符串文字中转义反斜杠。 So "\\\\s" instead of "\\s" , as the latter would be exactly the same as "s" . 所以用"\\\\s"代替"\\s" ,因为后者与"s"完全相同。 Also, the colon was missing in your regular expression. 另外,您的正则表达式中缺少冒号。 Finally, you had a spelling mistake in the length property name, so your if condition would always be false. 最后,您在length属性名称中存在拼写错误,因此if条件始终为false。

Be aware that exec and match will return null when there is no match, so you should not assume there is a length property. 请注意,如果没有匹配项,则execmatch将返回null ,因此您不应假定存在length属性。

This approach returns an object with all the found key/value pairs. 此方法返回具有所有找到的键/值对的对象。 From there, you can search for any key you want. 在这里,您可以搜索所需的任何键。

 var text = "<!-- Name:Peter Smith --><!-- Age:23 --><!-- Key with space : yes -->"; var data = ExtractData(text); console.log(data); console.log("Extracted name: (" + data["Name"] + "), age: (" + data["Age"] + ")"); function ExtractData(data) { var matches = data.match(/([A-Za-z\\s]+:[^\\-\\-\\>]+)/g); var data = {}; if (Array.isArray(matches)) { matches.forEach(function(match) { var pair = match.split(":"); if (pair.length === 2) { data[pair[0].trim()] = pair[1].trim(); } }); } return data; } 

Instead of regex, you can use string split function. 可以使用字符串拆分功能代替正则表达式。

var text = "<!-- Name:Peter Smith --><!-- Age:23 -->"; // Data to be scanned
var obj = ExtractToObj(text);
document.getElementById("result").innerHTML = "Extracted name: (" + obj["Name"] + "), age: (" + obj["Age"] + ")";

function ExtractToObj(data) {
  var obj = {};
  var kvps = data.split("-->").filter(function(n) {
    return n !== ""; // remove empty elements
  });
  for (var i = 0; i < kvps.length; i++) {
    var kvp = kvps[i].split(":");
    var key = kvp[0].replace("<!--", "").trim();
    var value = kvp[1].trim();
    obj[key] = value;
  }
  return obj;
}

https://jsfiddle.net/ydjbc4yq/ https://jsfiddle.net/ydjbc4yq/

I would do something like this: 我会做这样的事情:

 const data = `<div><!-- Name : Peter Smith --><!-- Age:23 -->some test data that is not found</div>` const getData = data => { const obj = {}, regex = /<!--\\s*(.*?)\\s*:\\s*(.*?)\\s*-->/g let temp while (temp = regex.exec(data)){ obj[temp[1]] = temp[2] } return obj } const personInfo = getData(data) console.log(`Extracted name: (${personInfo.Name}), age: (${personInfo.Age})`) 

Or if you want to extract only one property: 或者,如果您只想提取一个属性:

 const data = `<div><!-- Name : Peter Smith --><!-- Age:23 -->some test data that is not found</div>` const getData = (data, key) => (data.match(new RegExp(`<!--\\\\s*${key}\\\\s*:\\\\s*(.*?)\\\\s*-->`)) || [, null])[1] console.log(`${getData(data, 'Name')}`) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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