Blog

Random thoughts from my head.

Regex To Parse Inches And Feet

Posted almost 7 years ago on 28th of March, 2017.
Regex To Parse Inches And Feet

If you are a developer and are not familiar with regex, you should look up a quick tutorial for it because parsing text becomes so much easier with it. I recently had to work on parsing text inputs with inches and feet and thought I’d share it here:

^(d+)('|")(?:([0-12]+)(?!2)")?$

This will capture the following examples:

10'
10'11"
100'12"
10'12"
11"
10'

But not the following ones:

12"23'
19'12'
ABC12'
10'13"

The last one is not captured because anything over 12 inches is going to be another feet, so it should be 11'1" instead. It contains the following capture groups:

Example 1: 10'12"

Example 2: 5"

Example 3: 6'

Group 1: If there is only feet or only inches in the search text, it gets the feet or inches (the number part), if there are both feet and inches, it gets the feet. In example 1 it would return 10, in example 2 it would return 5 and in example 3 it would return 6.

Group 2: Gets either ' or " so you can check if the entry was feet or inches if there was only feet or only inches in the text. In example 1 and 3 it would return '. In example 2 it would return ".

Group 3: If the text has both feet and inches, gets the inches part. In example 1, it would return 12, in example 2 and 3 it would not exist.

This should work in JavaScript as well as most regex engines. It can be used to validate user input or to extract data (parse).

 View Other Posts