简体   繁体   English

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

[英]Javascript Regex multiple group matches in pattern

I have a question for a Javascript regex ninja: How could I simplify my variable creation from a string using regex grouping? 我有一个关于Javascript正则表达式忍者的问题:如何使用正则表达式分组从字符串中简化变量创建? I currently have it working without using any grouping, but I would love to see a better way! 我目前没有使用任何分组工作,但我希望看到更好的方式!

The string is: 字符串是:

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

The code that works is: 有效的代码是:

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

This gives: 这给出了:

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

Any takers? 任何接受者?

Sure.. 当然..

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];
#(?<type>.+){(?<property>.*?):(?<value>.*?);

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

[Jay loves regexbuddy] [周杰伦喜欢regexbuddy]

JS: JS:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM