如何打印包含特定字符串的行?

时间:2017-03-31 16:47:40

标签: javascript node.js regex

我想在字符串中打印包含日期的行,我使用split模块来完成该任务。下面的代码总是打印else语句。

ctrl.js

fs.readFile(dir + '/' + logFile, 'utf8', function(err, data) {
        var lines = data.split('\n');
        var linesWithDate = lines.split('|')[0].replace(/[\[\]']+/g,'');
        lines.forEach(function(line) {
            if (linesWithDate) {
                console.log('print lines with date',line);
             } else {
                console.log('print lines without date',line);
             }
        }
    });

档案数据

[2017-03-23T18:13:16Z]|zlpv7490|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event lorem ipsum
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy 
[2017-03-23T19:20:16Z]|zlpv7490|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event lorem ipsum

2 个答案:

答案 0 :(得分:1)

  

如何打印包含特定字符串的行?

const split = require('split');
fs.createReadtStream(path.join(dir, logFile), 'utf8')
  .pipe(split()).on('data', (line) => {
    if (line.indexOf('string') > -1) {
        console.log('Line with string:', line);
    } else {
        console.log('Line without string:', line);
    }
});
  

我想在字符串中打印包含日期的行,我使用split模块来完成该任务。下面的代码总是打印else语句

我认为你没有使用split模块。这个例子确实:

const split = require('split');
const regex = require('regex-iso-date');
fs.createReadtStream(path.join(dir, logFile), 'utf8')
  .pipe(split()).on('data', (line) => {
    if (regex().test(line)) {
        console.log('Line with date:', line);
    } else {
        console.log('Line without date:', line);
    }
});

请注意,这不一定是有效日期,因为它可能与2017-13-13之类的日期相符... - 测试有效日期只能看到这个答案:

或者,如果您想匹配[2017-03-23T18:13:16Z]这样的特定字符串,那么您可以尝试这样的事情:

const split = require('split');
const regex = /\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\w+\]/;
fs.createReadtStream(path.join(dir, logFile), 'utf8')
  .pipe(split()).on('data', (line) => {
    if (regex.test(line)) {
        console.log('Line with date:', line);
    } else {
        console.log('Line without date:', line);
    }
});

请注意,如果您的文件中包含无效日期,它也会匹配无效日期。

答案 1 :(得分:0)

这是一些代码,它只按行打印出有效的解析日期。我使用readline模块而不是readfile,但您应该可以通过替换input: process.stdin来轻松调整逻辑:     'use strict';

var sExample = '[2017-03-23T18:13:16Z]|zlpv7490|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event lorem ipsum';

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.setPrompt('Enter example string to test > ');
rl.prompt();

rl.on('line', (line) => {
  var sCandidate = line.split('|')[0].replace(/[\[\]']+/g,'');

  if (Date.parse(sCandidate)) {                   //it is a valid date
    console.log(sCandidate);
  }

  process.exit(0);
});