网站搜索

Javascript 正则表达式模式中的多个分组匹配


我有一个关于 Javascript 正则表达式高手的问题:我如何使用正则分组来简化从字符串创建变量的过程?我目前在不使用任何分组的情况下已经可以实现,但我很想看看有没有更好的方法!

字符串是:

var url = 'resources/css/main.css?detect=#information{width:300px;}';

有效的代码是:

var styleStr = /[^=]+$/.exec(url).toString();
var id = /[^\#][^\{]+/.exec(styleStr).toString();
var property = /[^\{]+/.exec(/[^\#\w][^\:]+/.exec(styleStr)).toString();
var value = /[^\:]+/.exec(/[^\#\w\{][^\:]+[^\;\}]/.exec(styleStr)).toString();

这给出:

alert(id)       //information
alert(property) //width
alert(value)    //300px

有人愿意吗?

答案#1

当然..

var url = 'resources/css/main.css?detect=#information{width:300px;}';
var matches = url.match(/#([^{]+){([^:]+):([^;]+)/);
var id = matches[1];
var property = matches[2];
var value = matches[3];

答案#2

#(?<type>.+){(?<property>.*?):(?<value>.*?);

Group "type":   information     31      11
Group "property":   width       43       5
Group "value":  300px

[杰伊爱RegexBuddy]

JS :

result = subject.match(/#([\s\S]+)\{([\s\S]*?):([\s\S]*?);/ig);