【问题标题】:Split text with regex in nodejs在nodejs中使用正则表达式拆分文本
【发布时间】:2022-07-29 18:19:36
【问题描述】:

我尝试在文件中查找 sql 脚本以在 nodejs 中拆分。在拆分为文本之前,我添加了 -split- 分隔符和正则表达式替换到 sql 脚本的开头,如下所示:

SQL 文件:

/* this is a comment for create table */
--this is another comment for create table

create table test1 (comment varchar);
create temporary table test2 (comment varchar);

insert into text1 values('this is a comment for create table ')

正则表达式替换操作:

sqlText
.replace(/\s+create(\s+|global\s+|temporary\s+)table\s+/gi, `-split- CREATE $1 TABLE `)

预期输出:

/* this is a comment for create table */
--this is another comment for create table

-split- CREATE TABLE test1 (comment varchar);
-split- CREATE temporary TABLE test2 (comment varchar);

insert into text1 values('this is a comment for create table ')

但我明白了:

/* this is a comment for -split- CREATE TABLE */
--this is another comment for -split- CREATE TABLE

-split- CREATE TABLE test1 (comment varchar);
-split- CREATE temporary TABLE test2 (comment varchar);

insert into text1 values('this is a comment for -split- CREATE TABLE ')

如何排除注释行和引号中的查询语句?

【问题讨论】:

    标签: javascript regex


    【解决方案1】:
    1. 首先将split文本分行.split(/\n/)
    2. 循环使用map 每行检查它的行是否以create table 开头,如果是,则根据需要更改-split- CREATE TABLE

    let sqlText = `/* this is a comment for create table */
    --this is another comment for create table
    
    create table test1 (comment varchar);
    create table test2 (comment varchar);
    
    insert into text1 values('this is a comment for create table ')
    `;
    console.log(sqlText.split(/\n/).map(line=>line.replace(/^create\s+table\s+/gi, `-split- CREATE TABLE `)).join('\n'))

    Notice: ^ 表示“以”开头。

    更新

    正则表达式标志m更简单

    console.log(sqlText.replace(/^create\s+table\s+/gmi, `-split- CREATE TABLE `))
                                                    ☝️
    

    【讨论】:

      【解决方案2】:

      使用

      const str = `/* this is a comment for create table */
      --this is another comment for create table
      
      create table test1 (comment varchar);
      create table test2 (comment varchar);
      
      insert into text1 values('this is a comment for create table ')`
      console.log(str.replace(/(\/\*[^]*?\*\/|^\s*--.*|'[^\\']*(?:\\[^][^\\']*)*'|"[^\\"]*(?:\\[^][^\\"]*)*")|[^\S\n\r]*create\s+table\s+/gmi, (_, x) => x || `-split- CREATE TABLE `))

      我们跳过多行 cmets (\/\*[^]*?\*\/)、单行 cmets (^\s*--.*)、单引号文字 ('[^\\']*(?:\\[^][^\\']*)*') 和双引号文字。

      [^\S\n\r]*create\s+table\s+ 正则表达式部分查找上述模式之外的匹配项。

      【讨论】:

      • 谢谢它的工作。如果createtable 之间有特定单词,我如何使用$1-$9 参数。喜欢create global tablecreate temporary table。替换语法为create(\s+|global\s+|temporary\s+)table
      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      相关资源
      最近更新 更多