在javascript中格式化文本

Posted

技术标签:

【中文标题】在javascript中格式化文本【英文标题】:Format text in javascript 【发布时间】:2019-09-10 15:19:05 【问题描述】:

如何在 javascript 中编写一个解析器/方法来解析下面的文本?

输入

  digraph "com.a:test:jar:1.0"  
     "com.a:test:jar:1.0" -> 
     "org.apache.httpcomponents:httpclient:jar:4.5.5:compile"; 
     "com.a:test:jar:1.0" -> "com.google.code.gson:gson:jar:2.8.2:compile"; 
     "com.a:test:jar:1.0" -> "info.picocli:picocli:jar:2.3.0:compile"; 
     "com.a:test:jar:1.0" -> "log4j:log4j:jar:1.2.17:compile"; 
     "com.a:test:jar:1.0" -> "org.xerial:sqlite-jdbc:jar:3.21.0:compile";
     "org.apache.httpcomponents:httpclient:jar:4.5.5:compile" -> 
     "org.apache.httpcomponents:httpcore:jar:4.4.9:compile" ; 
     "org.apache.httpcomponents:httpclient:jar:4.5.5:compile" -> "commons-logging:commons-logging:jar:1.2:compile" ; 
     "org.apache.httpcomponents:httpclient:jar:4.5.5:compile" -> "commons-codec:commons-codec:jar:1.10:compile" ; 
      

所需的输出

 digraph "com.a:test:jar:1.0"  
         "com.a:test:jar:1.0" -> 
         "org.apache.httpcomponents:httpclient:jar:4.5.5:compile"; 
         "com.a:test:jar:1.0" -> "com.google.code.gson:gson:jar:2.8.2:compile"; 
         "com.a:test:jar:1.0" -> "info.picocli:picocli:jar:2.3.0:compile"; 
         "com.a:test:jar:1.0" -> "log4j:log4j:jar:1.2.17:compile"; 
         "com.a:test:jar:1.0" -> "org.xerial:sqlite-jdbc:jar:3.21.0:compile";
          

即出现在图表“com.a:test:jar:1.0”旁边的任何内容,如果它出现在 (LHS) -> 之前,则忽略它。

注意:有向图可以有多个块。

【问题讨论】:

【参考方案1】:

您可以使用正则表达式进行部分解析,并使用replace 回调来保留/消除相关部分:

function clean(input) 
    let keep;
    return input.replace(/^\s*digraph\s+("[^"]*")\s*\|\s*("[^"]+")\s*->\s*"[^"]+"\s*;|([^])/gm, 
        (m, a, b, c) => a && (keep = a) || b === keep || c ? m : ""
    );


// Example:
var input = `digraph "com.a:test:jar:1.0"  
     "com.a:test:jar:1.0" -> 
     "org.apache.httpcomponents:httpclient:jar:4.5.5:compile"; 
     "com.a:test:jar:1.0" -> "com.google.code.gson:gson:jar:2.8.2:compile"; 
     "com.a:test:jar:1.0" -> "info.picocli:picocli:jar:2.3.0:compile"; 
     "com.a:test:jar:1.0" -> "log4j:log4j:jar:1.2.17:compile"; 
     "com.a:test:jar:1.0" -> "org.xerial:sqlite-jdbc:jar:3.21.0:compile";
     "org.apache.httpcomponents:httpclient:jar:4.5.5:compile" -> 
     "org.apache.httpcomponents:httpcore:jar:4.4.9:compile" ; 
     "org.apache.httpcomponents:httpclient:jar:4.5.5:compile" -> "commons-logging:commons-logging:jar:1.2:compile" ; 
     "org.apache.httpcomponents:httpclient:jar:4.5.5:compile" -> "commons-codec:commons-codec:jar:1.10:compile" ; 
      `

console.log(clean(input));

【讨论】:

以上是关于在javascript中格式化文本的主要内容,如果未能解决你的问题,请参考以下文章

javascript:void 含义

在javascript中格式化文本

JavaScript中“javascript:void ”是什么意思

函数js

Javascript选择文本并格式化textarea

如何在javascript中读取本地的json格式文本文件