Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? 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?

like image 718
mummybot Avatar asked May 18 '10 15:05

mummybot


People also ask

How do Capturing groups work in regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d" "o" and "g" .

How do I match a group in regex?

Regular expressions allow us to not just match text but also to extract information for further processing. This is done by defining groups of characters and capturing them using the special parentheses ( and ) metacharacters. Any subpattern inside a pair of parentheses will be captured as a group.

What is capturing group in regex Javascript?

Groups group multiple patterns as a whole, and capturing groups provide extra submatch information when using a regular expression pattern to match against a string. Backreferences refer to a previously captured group in the same regular expression.

What is first capturing group in regex?

/^(\d+)\s\1\s\1$/ this regex explains: (i) a caret ( ^ ) is at the beginning of the entire regular expression, it matches the beginning of a line. (ii) (\d+) is the first capturing group that finds any digit from 0-9 appears at least one or more times in the string.


2 Answers

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];
like image 189
Matt Avatar answered Oct 04 '22 06:10

Matt


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

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

[Jay loves regexbuddy]

JS:

result = subject.match(/#([\s\S]+)\{([\s\S]*?):([\s\S]*?);/ig);
like image 32
Glycerine Avatar answered Oct 04 '22 06:10

Glycerine