gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:41:51 24 4
gpt4 key购买 nike

我喜欢通过 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('脚本', 数组(

));

有人知道正确的正则表达式吗?
我是正则表达式新手。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'));
});

最佳答案

此代码段(在 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}`);
});
}

关于javascript 正则表达式从 config.php 字符串中提取路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43690657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com