dqyknf4423 2017-04-29 00:38
浏览 72
已采纳

javascript正则表达式从config.php字符串中提取路径

i like to minify all js-files from a config.php by gulp.

//config.php
c::set('myvar', true);

c::set('styles', [
  'test1.css',
  'test2.css'
]);

c::set('scripts', array(
  'node_modules/abc.min.js',
  'node_modules/def.js',
  'assets/js/xyz.js' 
));

i read the file by fs.readFile to a string. so far so good.
unfortunately i can't find the correct regex/match to get only the paths between:

c::set('scripts', array(

and

));

anybody knows the right regex?
i am regex newbie. tnx

Update

With the regex from @Ken following the working solution:

var gulp = require('gulp'),
    fs = require("fs"),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify');

var jsfromconfigphp = [];

gulp.task('get-js-by-config-php', function(done) {
  const regex = /\s+(\'[\w\/\.]+\.js\')/gi;
  let m;
  fs.readFile('site/config/config.php', {encoding: 'utf-8', flag: 'rs'}, function(e, data) {
    if (e) {
      return console.log(e);
    }
    while ((m = regex.exec(data)) !== null) {
      // This is necessary to avoid infinite loops with zero-width matches
      if (m.index === regex.lastIndex) {
        regex.lastIndex++;
      }
      // The result can be accessed through the `m`-variable.
      m.forEach((match, index) => {
        if(index === 1) {
          console.log(`Found match, group ${index}: ${match}`);
          jsfromconfigphp.push(match.slice(1, -1));
        }
      });
    }
    done();
  });
});

// wait for get-js-by-config-php is done
gulp.task('build-js', ['get-js-by-config-php'], function() {
  return gulp.src(jsfromconfigphp)
  .pipe(concat('main.min.js'))
  .pipe(uglify({
    compress: {
      drop_console: true
    }
  }))
  .pipe(gulp.dest('assets/js'));
});
  • 写回答

2条回答 默认 最新

  • dongzhugao9929 2017-04-29 01:27
    关注

    This snippet (with help from regex101.com) outputs the strings - does it meet your needs?

    const regex = /\s+(\'[\w\/]+\.js\')/gi;
    const str = `c::set('myvar', true);
    
    c::set('styles', [
      'test1.css',
      'test2.css'
    ]);
    
    c::set('scripts', array(
      'node_modules/abc.js',
      'assets/js/xyz.js' 
    ));`;
    let m;
    
    while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        
        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
        });
    }

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向