【问题标题】:I have multiple lines of string now i want to print those lines who contains particular substring我有多行字符串现在我想打印那些包含特定子字符串的行
【发布时间】:2019-02-25 18:33:58
【问题描述】:
Here i want to print line which contains following strings: 
Object.< anonymous > 

这是多行:现在找到那些包含子字符串 Object 的行。

Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'yourusername'@'localhost' (using password: YES)
at Socket.< anonymous > (/home/abc/Desktop/AJ/CustomLogger/node_modules/mysql/lib/Connection.js:91:28)
at Object.< anonymous > (/home/abc/Desktop/AJ/CustomLogger/conn.js:10:5)
at Module._compile (internal/modules/cjs/loader.js:686:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)

输出应该是: 在 Object. (/home/abc/Desktop/AJ/CustomLogger/conn.js:10:5)

【问题讨论】:

    标签: javascript arrays node.js string npm


    【解决方案1】:

    您可以拆分字符串并首先获取所有行,然后检查Object.&lt; anonymous &gt;(有或没有regex) 过滤掉它们。

    let str = `Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'yourusername'@'localhost' (using password: YES)
    at Socket.< anonymous > (/home/abc/Desktop/AJ/CustomLogger/node_modules/mysql/lib/Connection.js:91:28)
    at Object.< anonymous > (/home/abc/Desktop/AJ/CustomLogger/conn.js:10:5)
    at Module._compile (internal/modules/cjs/loader.js:686:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)`,
    
    res = str.split("\n").filter(line=>line.indexOf("Object.< anonymous >")>-1);
    
    console.log(res);

    或者,您可以匹配带有多行标志的regex (m)

    let str = `Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'yourusername'@'localhost' (using password: YES)
    at Socket.< anonymous > (/home/abc/Desktop/AJ/CustomLogger/node_modules/mysql/lib/Connection.js:91:28)
    at Object.< anonymous > (/home/abc/Desktop/AJ/CustomLogger/conn.js:10:5)
    at Module._compile (internal/modules/cjs/loader.js:686:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)`,
    
    res = str.match(/^(.*Object\.< anonymous >.*)$/mg);
    
    console.log(res);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 2021-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多