我想使用javascript从字符串中获取多个变量。
字符串示例:
<span var1="abc" some random thing var2="cde" another random stuff var3="efg"></span>
<span var1="abc" some random thing var2="cde" another random stuff??>
<::" var3="efg"></span>
我想获得var1
,var2
和var3
。
我最接近第一组使用此正则表达式。
span var1="(.*?)"(?:.*)var2="(.*?)"(?:.*)var3="(.*?)"(?:.*)\/span
以下是示例: Example
谢谢!
答案 0 :(得分:0)
我错过了什么吗?你的代码适合我。
请参阅以下示例:
var str = '<span var1="abc" some random thing var2="cde" another random stuf var3="efg"></span><span var1="abc" some random thing var2="cde" another random stuf??><::" var3="efg"></span>';
var re = /<span var1=["'](.*?)["'](?:.*)var2=["'](.*?)["'](?:.*)var3=["'](.*?)["'](?:.*)\/span>/;
var matches = re.exec(str).slice(1);
matches.forEach(function(match) {
document.body.insertAdjacentHTML('beforeend', match + '<br>');
});
答案 1 :(得分:0)
您需要的是正则表达式的exec
方法。它允许您重复获取子匹配,继续在最后一场比赛后的位置。
我做了什么:
regex.exec
代替string.match
g
来制作正则表达式全局(?:.*)
更改为.*?
,因为它过于贪婪并且吃掉了中间的所有内容现在它可以工作(jQuery只是为了输出的简单可视化):
var str = '<span var1="abc" some random thing var2="cde" another random stuf var3="efg"></span><span var1="abc" some random thing var2="cde" another random stuf??><::" var3="efg"></span>';
// Note that I added "g" to make it a global selector and changed all (?:.*) to .*?
var re = /<span var1="(.*?)".*?var2="(.*?)".*?var3="(.*?)".*?\/span>/g;
var matches;
// You can call re.exec repeatedly and it will return always the next group of results
while(matches = re.exec(str)) {
// matches will look like this: ["<span var1="abc" some random thing var2="cde" another random stuf var3="efg"></span>", "abc", "cde", "efg", index: 0, input: "<span var1="abc" some random thing var2="cde" anot…de" another random stuf??><::" var3="efg"></span>"]
// This is just for nice output
$("<span/>").text(matches[0]).appendTo("body");
$("<ul/>").append(matches.slice(1).map(function(m) {
return $("<li/>").text(m);
})).appendTo("body");
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
如果你想要少一点&#34;僵硬&#34;只需查找看起来的任何内容,就像带引号的HTML属性一样,您可以使用此正则表达式:/\s([\w-]+)="(.*?)"/g
。
答案 2 :(得分:0)
编辑请参阅REGEX 101 DEMO。你可以尝试:
gulp.task('unit-test', ['lint'], function (done) {
gulputil.log('Running unit tests...');
//return gulp.src(testFilesDirect).pipe(jasmine({ verbose: true, includeStackTrace: true }));
new KarmaServer({
configFile: __dirname + '/karma.conf.js',
files: ['/tests/*.spec.js', '/tests/**/*.spec.js'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
}, done).start();
});