使用JS regex从textfile中提取字符串

时间:2015-06-15 18:47:03

标签: javascript regex

我尝试使用Javascript Regex从文件中提取子字符串。这是文件中的一个切片:

Version=2

Format=jpg

Size=1280x960

Date=2013/05/08

Time=23:49:40

Value=250000

我想从文本文件中仅提取VersionValue。 我尝试使用它来提取版本,但它没有返回任何内容。

$('.Content').html().match(/^Version\:(.*)$/g);

$('.Content').html()包含整个文本文件。

6 个答案:

答案 0 :(得分:1)

它没有返回任何内容,因为您在正则表达式中使用:而不是=

答案 1 :(得分:1)

您必须删除锚点或使用m标志:

$('.Content').html().match(/Version=(.*)/g);

或者

$('.Content').html().match(/^Version=(.*)$/gm);

编辑:要捕获价值和版本,您可以执行以下操作:

$('.Content').html().match(/Version=(.*)|Value=(.*)/g);

您将获得$1中的版本和$2

中的值

请参阅DEMO

答案 2 :(得分:1)

如果您只需要Version,那么这里还有很多其他答案。

如果你需要解析整个文件,可以使用类似的东西

var re = /^(\w+)=(.*)$/gm;
var result = {};
var match;

while (match = re.exec(str)) {
  result[match[1]] = match[2];
}

console.log(result.Version);
//=> "2"

console.log(result.Value);
//=> "250000"

console.log(JSON.stringify(result));
// {
//   "Version": "2",
//   "Format": "jpg",
//   "Size": "1280x960",
//   "Date": "2013/05/08",
//   "Time": "23:49:40",
//   "Value": "250000"
// }

答案 3 :(得分:0)

您的正则表达式应该是:( :替换=,最后删除$g

/^Version=(.*)/

答案 4 :(得分:0)

您可以使用此正则表达式:

/(Version|Value)=(.*)/gm

答案 5 :(得分:0)

更改:的{​​{1}}并添加=标记。

m

演示:

^(?:Version|Value)=(.*)$/gm
$( document ).ready(function() {
  var re = /^(?:Version|Value)=(.*)$/gm; 
  var str = $('.Content').html();
  var m;
  var result = "";
 
  while ((m = re.exec(str)) !== null) {
      if (m.index === re.lastIndex) {
          re.lastIndex++;
      }
    result += m[1] + ", ";
    
}
  $('#result').text(result);
});