简体   繁体   English

使用JS正则表达式从文本文件中提取字符串

[英]Extract a string from textfile using JS regex

I'm trying to extract a substring from a file with Javascript Regex. 我正在尝试使用Javascript Regex从文件中提取子字符串。 Here is a slice from the file : 这是文件中的一个片段:

Version=2

Format=jpg

Size=1280x960

Date=2013/05/08

Time=23:49:40

Value=250000

I want to extract only Version and Value from the text file. 我只想从文本文件中提取VersionValue I tried extracting the Version using this but it doesn't return anything. 我尝试使用此方法提取版本,但它不返回任何内容。

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

$('.Content').html() contains the whole text file. $('.Content').html()包含整个文本文件。

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

You have to remove the anchors or use m flag: 您必须删除锚点或使用m标志:

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

Or 要么

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

Edit: For capturing Value and Version you can do the following: 编辑:对于捕获值和版本,您可以执行以下操作:

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

You will get Version in $1 and Value in $2 您将在$1获得版本,在$2获得价值

See DEMO 演示

If you only need the Version , there's plenty of other answers here. 如果只需要Version ,这里还有很多其他答案。

If you need to parse the entire file, maybe use something like this 如果您需要解析整个文件,则可以使用如下所示的内容

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"
// }

您的正则表达式模式应为:(替换: by =并在最后删除$g

/^Version=(.*)/

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

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

Change : for = and add m flag. 更改: for =并添加m标志。

^(?:Version|Value)=(.*)$/gm

Demo: 演示:

 $( 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); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="Content"> Version=2 Format=jpg Size=1280x960 Date=2013/05/08 Time=23:49:40 Value=250000 </div> <br> <div id="result">test</div> 

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

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