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?
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" .
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.
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.
/^(\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.
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]
JS:
result = subject.match(/#([\s\S]+)\{([\s\S]*?):([\s\S]*?);/ig);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With