diff --git a/Akash Articles/RegEx/named_groups.html b/Akash Articles/RegEx/named_groups.html new file mode 100644 index 0000000..8ec64f8 --- /dev/null +++ b/Akash Articles/RegEx/named_groups.html @@ -0,0 +1,90 @@ + +
+ + + + + + + + + + +Regular expressions with lots of groups and backreferencing can be difficult to maintain, as adding or removing a capturing group in the middle of the regex turns to change the numbers of all the groups that follow the added or removed group.
+ +In regex, we have facility of named groups, which solves the above issue. Let's look at it.
+ +We can name a group by putting ?<name>
just after opening the paranthesis representing a group. For example, (?<year>\d{4})
is a named group.
Below is a code, we have already looked in capturing groups part. You can see, the code is more readable now.
+ + var str = "2020-01-20";
+
+ // Pattern string
+ var pattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g;
+
+ // ^ ^ ^
+ //group-no: 1 2 3
+
+ // Data replacement using $<group_name>
+ var ans=str.replace(pattern, '$<day>-$<month>-$<year>');
+
+ console.log(ans);
+ // Output will be: 20-01-2020
+
+
+ Backreference syntax for numbered groups works for named capture groups as well. \k<name>
matches the string that was previously matched by the named capture group name
, which is a standard way to backreference named group.