Reputation: 555
Hi guys I want re use the expression for capture other group
For example:
I need search US $4.5-8.8
The structure is: Part1-Part2
The part1 and the part2 have the same code, I could use the part1 like group, and then re use in the part2
I've doned the expression until 4.5-XXXX
US \$([0-9]{1}(?=\.{1})\.{1}[0-9]+)(?=\-)\-
check in: https://regex101.com/r/E2MjWh/1
What should I do for re use the first group? It is easy in other lenguague, but I can't do it in javascript..
PD: I need it in regex, not include javascript code like var... etc etc..
Upvotes: 1
Views: 51
Reputation: 626794
First, have a look at your regex: the positive lookaheads are not really necessary there as they just require the same as the following consuming subpatterns. (?=\.{1})\.{1}
means *require 1 dot immediately to the right of the current location and then match the dot, and (?=\-)\-
has a similar meaning requiring and matching a -
symbol.
Now, you ask if you can repeat the same part of a pattern using just the regex syntax. No, it is not possible in JS regex.
You may use the following regex to match the whole string like yours:
/US\s+\$(\d+\.\d+)-(\d+\.\d+)/
See the regex demo. Sure, you may add word boundaries (to match US
as a whole word) or anchors (to match the whole input string) or replace the \d+\.\d+
part with \d*\.?\d+
(to match both integers or floats) to further enhance the pattern.
There is a way to shorten the pattern by placing the repetitive part into a variable and build the regex dynamically using the constructor notation:
var price = "\\d*\\.?\\d+";
var reg = new RegExp("US\\s+\\$(" + price + ")-(" + price + ")");
Add the required modifiers if necessary.
Upvotes: 1