'Regex (JavaScript): match feet and/or inches
I'm trying to match feet and inches but I can't manage to get "and/or" so if first half is correct it validates:
Code: (in javascript)
var pattern = "^(([0-9]{1,}\')?([0-9]{1,}\x22)?)+$";
function testing(input, pattern) {
var regex = new RegExp(pattern, "g");
console.log('Validate '+input+' against ' + pattern);
console.log(regex.test(input));
}
Valid tests should be:
1'1'2"2"2(assumes inches)
Not valid should be:
* anything else including empty
* 1'1'
But my regex matches the invalid 1'1'.
Solution 1:[1]
try this
var pattern = "^\d+(\'?(\d+\x22)?|\x22)$";
Solution 2:[2]
Not to resurrect the dead, but here was my best shot at detecting fractional feet and inches. It will find:
- 3'
- 3'-1" or 3' 1"
- 3'-1 1/2" or 3' 1 1/2"
- 3'-1/2", 3' 1/2", 3'-0 1/2", or 3'0 1/2"
- 1"
- 1/2"
The only catch is your flavor of regex has to support conditionals.
pattern = "(\d+')?(?:(?(1)(?: |\-))(\d{1,2})?(?:(?(2) )\d+\/\d+)?\x22)?"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
