Regular Expressions 101

Community Patterns

Community Library Entry

0

Regular Expression
ECMAScript (JavaScript)

/
^(?<pre>\D*?)(?<num>\d*\.\d+|\d+\.\d*|\d+)(?<sp>\s*?)(?<units>bytes|kb|mb|gb|tb|b|k|m|g|t)$
/
gi

Description

Purpose

This pattern is used to parse human readable text strings regarding file sizes.

The pattern names four capture groups in the string for the following purposes:

  • pre: any text before the numeric characters begin are captured and filtered out
  • num: matches any real number with or without a decimal point. ex: [1.3, 0.19, .6, 21., 42]
  • sp: captures whitespace between numeric characters and units
  • units: captures alpha text to match with units resolver

The "pre" and "sp" captures can be discarded. The num capture can be changed to numeric with a parseFloat. The units capture can be used to determine any unit conversions required.

Submitted by Vincent Engler - 3 years ago (Last modified 8 months ago)