Height is a measure of how tall an object or person is. It is typically measured in units of length, such as inches or centimeters. In this article let’s understand how we can create a regex for matching height in cms from a string and how regex can be matched for height in cms.
Regex (short for regular expression) is a powerful tool used for searching and manipulating text. It is composed of a sequence of characters that define a search pattern. Regex can be used to find patterns in large amounts of text, validate user input, and manipulate strings. It is widely used in programming languages, text editors, and command line tools.
Structure of Height in feet and inches
- It should start with digits
- It can be followed by a
.
- It can optionally have a decimal digits after the
.
- It should be accompanied by a unit of measurement cm
Regex for matching Height in feet and inches from a string
Regular Expression-
/\d+ft\ {0,1}\d{1,2}in$/gm
Test string examples for the above regex-
Input String | Match Output |
---|---|
1233 | does not match |
You are 6ft 2in tall | matches |
random | does not match |
5ft 6in | matches |
Here is a detailed explanation of the above regex-
/\d+ft\ {0,1}\d{1,2}in$/gm
\d matches a digit (equivalent to [0-9])
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
ft matches the characters ft literally (case insensitive)
f matches the character f with index 10210 (6616 or 1468) literally (case insensitive)
t matches the character t with index 11610 (7416 or 1648) literally (case insensitive)
\ matches the character with index 3210 (2016 or 408) literally (case insensitive)
{0,1} matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
\d matches a digit (equivalent to [0-9])
in matches the characters in literally (case insensitive)
$ asserts position at the end of a line
Global pattern flags
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
Hope this article was useful to match height in feet(ft) and inches(in) regex pattern. In conclusion, understanding how to create and utilize regular expressions (regex) for matching height in centimeters (cms) from a string is a valuable skill. Regex serves as a powerful tool for text manipulation and pattern recognition in programming, text editing, and more. By following the structured approach outlined in this article, you can effectively extract and validate height values in the desired format.