I am new to regex, and I am trying to create a regular expression to match a string that holds a measurement expressed in feet and inches with the possibility of fractional values in the inches. So far, I have the following expression:
var rex =/\s*(\d+)?\s*(?:'|ft|ft.|feet)?\s*-?\s*(\d+)?\s*(\d+)?\/?(\d+)?\s*(?:''|"|in|in.|inches)?/
To be as flexible as possible I made all the captures optional to set measurements like 1ft or 5'' as valid input data.
var mstring = '5in';
var match = rex.exec(mstring);
The problem is that when the regex is applied, for example to 5in the capture that I get is match[1]='5' while the other three values (match[2], match[3] and match[4]) remain undefined.
Is there a way that the captured values appear in the order they are defined?
In the above mentioned case, it will be that match[2]="5in" while match[1], match[3] and match[4] remain undefined.
The trick is in using non-capturing groups around the optional parts and using obligatory subpatterns inside those groups:
var rex =/(?:\s*(\d+)\s*(?:feet|ft\.|ft|'))?(?:\s*-\s*(\d+))?(?:\s*(\d+)\/)?(?:(\d+)\s*(?:inches|in\.|in|''|"))?/
In Group 1, I made (?:feet|ft\.|ft|') obligatory, in Group 2, it is the hyphen -, in Group 3, the slash /, and in Group 4, it is the (?:inches|in\.|in|''|") alternation.
See demo
I do not understand the logic now, but if you want 5 in 5in to appear in the 2nd group, use
(?:\s*(\d+)\s*(?:feet|ft\.|ft|'))?(?:\s*-?\s*(\d+))?(?:\s*(\d+)\/)?(?:(\d+)\s*(?:inches|in\.|in|''|"))?
^
See Demo 2
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