Weight is a measure of how heavy an object is. It is typically measured in units of mass, such as pounds or kilograms. In this article let’s understand how we can create a regex for matching weight in kgs from a string and how regex can be matched for weight in kgs.
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 Weight in kilogram (kg)
- 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 kg
Regex for matching Weight in kilogram (kg) from a string
Regular Expression-
/\d+\.{0,1}\d{1,3}kg$/gm
Test string examples for the above regex-
Input String | Match Output |
---|---|
1233 | does not match |
You are 170kg tall | matches |
random | does not match |
22.31kg | matches |
Here is a detailed explanation of the above regex-
/\d+\.{0,1}\d{1,3}kg$/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)
\. matches the character . with index 4610 (2E16 or 568) 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])
{1,3} matches the previous token between 1 and 3 times, as many times as possible, giving back as needed (greedy)
kg matches the characters kg 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 weight in kilogram(kg) regex pattern. In conclusion, understanding and using regular expressions (regex) can greatly enhance our ability to manipulate and extract specific patterns from text. In the context of matching weights in kilograms (kg) from strings, the provided regex pattern, /\d+.{0,1}\d{1,3}kg$/gm, offers a robust solution. By following the defined structure for weight representation and utilizing the power of regex, we can accurately identify and work with weight values in various programming and text-processing scenarios.