Reputation: 49
With some addresses a building might take up multiple door numbers for example 13 - 15 StreetName. The "13 - 15" is the part I am focusing on. How would you do a regular expression to pick out this part.
I thought something like [0-9] - [0-9] which works for 1 - 3 but if the address was 12 - 13 [0-9][0-9] - [0-9][0-9] could work but then I want to make sure that something like 13 - 3 wouldnt work as the addresses cannot go backwards and something like 99 - 103 would also work where the numbers are different lengths. Is it really simple and I'm missing something?
I'm still a student and not very good at regular expressions, I just need it for some js I'm doing and have spent far too long getting nowhere.
Thank you.
Upvotes: 0
Views: 345
Reputation: 64715
I don't think this is even possible with regex. I would instead just do something like this:
var addresses = [
"12 - 14 State St.",
"14 - 12 State St.",
];
addresses.forEach(address => console.log(validAddress(address)));
function validAddress(address) {
return !!(address.match(/\d+\s?-\s?\d+/) || []).filter(a => {
var numbers = a.split('-').map(b => b.trim());
return (numbers.length && numbers[0] < numbers[1]);
}).length;
}
Upvotes: 1
Reputation: 80111
There's not really a good way to do this since you're effectively trying to parse something that is not a regular language. Referencing something that you've seen before is allowed by several regular expression languages though, but that won't help you in this specific case.
We can easily go for the brute-force solution though :)
https://regex101.com/r/4bRmiL/1
^(\d{3} - \d{3,}|\d{2} - \d{2,}|\d - \d+)$
As you can see though, it still breaks for cases like 5 - 1
which are probably invalid. That's something you need to check outside of the regex.
Upvotes: 2