Javascript正则表达式多组匹配模式

时间:2010-05-18 15:48:05

标签: javascript regex grouping

我有一个关于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

任何参赛者?

2 个答案:

答案 0 :(得分:6)

不确定..

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];

答案 1 :(得分:1)

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

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

[Jay喜欢regexbuddy]

JS:

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