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

时间:2017-04-29 00:38:44

标签: javascript php regex gulp

我想通过gulp缩小config.php中的所有js文件。

//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' 
));

我通过fs.readFile将文件读取为字符串。到目前为止一切顺利。
不幸的是,我无法找到正确的正则表达式/匹配,只能获得之间的路径:

c :: set('scripts',array(

));

有谁知道正确的正则表达式?
我是正念我新手。 TNX

更新

来自@Ken的正则表达式遵循工作解决方案:

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 个答案:

答案 0 :(得分:0)

此片段(在regex101.com的帮助下)输出字符串 - 它是否符合您的需求?



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}`);
    });
}




答案 1 :(得分:0)

实现同样事情的替代方式

var path = "c::set('scripts', array('node_modules/abc.js','assets/js/xyz.js'));";
path = path.replace("c::set('scripts', array(",'')
path = path.replace('));','')
path.replace(/["']/g, "").split(',')