Reputation: 137
I have some simple text I'm trying to parse:
total 4.0K
-rw-rw-r-- 1 346 Mar 1 08:50 save_1
-rw-rw-r-- 1 0 Feb 28 17:28 save_2
-rw-rw-r-- 1 0 Feb 28 17:28 save_3
And I have a regular expression that I have tested working on different regex testing websites:
\w{3}\s+\d{1,2}\s\d{2}\:\d{2}\s\w{4}\_\d
I'm trying to take the sample text as an input in the following function in a Node.js application and return an object or array with the 3 different matches, from the month to the end of the line.
function parse(str) {
var regex = new RegExp("\w{3}\s+\d{1,2}\s\d{2}\:\d{2}\s\w{4}\_\d");
return regex.test(str);
//return str.match(regex);
}
I don't understand why the boolean from .test() is false and the object from .match() is null.
Any help would be greatly appreciated.
Upvotes: 1
Views: 2807
Reputation: 32701
Instead of trying to parse the output of ls
, which is bad, you should simply use file system operation provided by node.js. Using file system operations you can be sure your program will work in (almost) any edge case as the output is well defined. It will even work in case the folder will contain more or less files than three in the future!
As you stated in the comments that you want the names and date / time of the files from a folder. So let us have a look at:
fs.readdir(path, callback)
: fs.readdir
will give you an array of filenames in the folder specified in path. You can pass them to fs.stat
to find out the mtime:
fs.stat(path, callback)
: fs.stat()
will give you an object of fs.Stats
which contains the mtime in the mtime
property.
So your code will look something like this afterwards:
fs.readdir('dir', function (err, files) {
for (var i = 0; i < files.length; i++) {
(function () {
var filename = files[i]
fs.stat('dir/' + filename, function (err, stats) {
console.log(filename + " was last changed on " + stats.mtime);
});
})();
}
});
The output is:
[timwolla@~/test]node test.js
5 was last changed on Fri Mar 01 2013 20:24:35 GMT+0100 (CET)
4 was last changed on Fri Mar 01 2013 20:24:34 GMT+0100 (CET)
2 was last changed on Fri Mar 01 2013 20:24:33 GMT+0100 (CET)
In case you need a return value use the respective Sync
-versions of these methods. These, however, will block your node.js eventing loop.
Upvotes: 3
Reputation: 13631
Your regex is failing as you need to escape the \
when passing a string to the RegExp constructor, i.e. \s
should be \\s
.
var regex = new RegExp( "\\w{3}\\s+\\d{1,2}\\s\\d{2}:\\d{2}\\s\\w{4}_\\d", "g" );
The g
flag is added to get all the matches.
Upvotes: 0