简体   繁体   中英

Extract a string from textfile using JS regex

I'm trying to extract a substring from a file with 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. 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.

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

You have to remove the anchors or use m flag:

$('.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

See DEMO

If you only need the Version , there's plenty of other answers here.

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.

^(?: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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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