简体   繁体   中英

Correct regex expression for searching with JavaScript

I have a text file as given below:

time: 2014-5-15 9:12:5,Temperature 24.3 C, Humidity 20.1 % RH, Light 760
time: 2014-5-15 9:12:7,Temperature 24.4 C, Humidity 20.2 % RH, Light 757
time: 2014-5-15 9:12:9,Temperature 24.3 C, Humidity 20.2 % RH, Light 764
time: 2014-5-15 9:12:11,Temperature 24.3 C, Humidity 20.2 % RH, Light 753
time: 2014-5-15 9:12:13,Temperature 24.3 C, Humidity 20.1 % RH, Light 764
time: 2014-5-15 9:12:15,Temperature 24.3 C, Humidity 20.2 % RH, Light 759

I am writing some code to search for the "time" value from each line in the file and send it to an array, named time. The code is given below:

var time=[];

time.push(Number(item.match(/time:(.\d+[.]\d+)/)[1]));
time.toString();                            

document.getElementById("chartContainer").innerHTML=time;

However, the time values are not being displayed on the webpage. Is there something wrong with the regex expression in item.match()? I am new to JavaScript and really do not know much about regex in JS. Please help.

I think it's better to be explicit with what you are matching. Also this solution will pull any datetimes from a row, even if the input format changes.

var time_regex = /(\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2})/;

// example
var lines = [
  "time: 2014-5-15 9:12:5,Temperature 24.3 C, Humidity 20.1 % RH, Light 760",
  "time: 2014-5-15 9:12:7,Temperature 24.4 C, Humidity 20.2 % RH, Light 757",
  "time: 2014-5-15 9:12:9,Temperature 24.3 C, Humidity 20.2 % RH, Light 764",
  "time: 2014-5-15 9:12:11,Temperature 24.3 C, Humidity 20.2 % RH, Light 753",
  "time: 2014-5-15 9:12:13,Temperature 24.3 C, Humidity 20.1 % RH, Light 764",
  "time: 2014-5-15 9:12:15,Temperature 24.3 C, Humidity 20.2 % RH, Light 759",
];

for (var i in lines) {
  var r = lines[i].match(time_regex);
  console.log(r);
}

// logs
// 2014-5-15 9:12:5 
// 2014-5-15 9:12:7 
// 2014-5-15 9:12:9 
// 2014-5-15 9:12:11 
// 2014-5-15 9:12:13 
// 2014-5-15 9:12:15 

No need for a regex if the input has uniform format.

Just use String.substring() and String.indexOf() to extract the time.

For example, you could grab everything from the 6th character to the first comma:

var comma = s.indexOf(',');
var time = s.substring(6, comma);

Isn't that a little easier to read and maintain?

try this:

var str = 'time: 2014-5-15 9:12:5,Temperature 24.3 C, Humidity 20.1 % RH, Light 760';
var params = str.replace('time: ', '').split(',');
var date = new Date(params[0]);

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