Skip to main content

match

match(text: String, regex: Regex<T>) : T?

Gets a record of captured data if text matches the structure specified by regex, or otherwise null.

See the regular expression guide.

Examples

ExampletextregexThe type of regexThe result of match(str, regex)
1"Jane is 32 years old"re`Jane is 32 years old`Regex<{}>{}
2"Jane is 33 years old"re`Jane is 32 years old`Regex<{}>null; i.e., no match
3"Name: Jane, Age: 32"re`Name: (\w+), Age: (\d+)`Regex<{"1": String, "2": String}>{"1": "Jane", "2": "32"}
4"Name: Jane, Age: 32"re`Name: (?<name>\w+), Age: (?<age:Number>\d+)`Regex<{name: String, age: Number}>{name: "Jane", age: 32}
5"Jane is 32 years old"re`(?<age:Number>\d+)|(?:(?<name>\w+) is (?<age:Number>\d+) years old)`Regex<{age:Number, name?:String}>Matches the first choice of the |, yielding {name: "Jane", age: 32}
6"32"re`(?<age:Number>\d+)|(?:(?<name>\w+) is (?<age:Number>\d+) years old)`Regex<{age:Number, name?:String}>Matches the second choice of the |, yielding {name: null, age: 32}
7"3x2"re`(?<age:Number>\d+)|(?:(?<name>\w+) is (?<age:Number>\d+) years old)`Regex<{age:Number, name?:String}>null; i.e., no match

Regexes with anonymous captures have match result record with indices as keys, and all values are of type String.

  • Matches of unnamed capture groups are referenced with string indices, such as "1" and not numbers such as 1.
  • For instance, in example 3 above, the regex has type Regex<{"1": String, "2": String}>. As such, match("Name: Jane, Age: 32", re`Name: (\w+), Age: (\d+)`)["2"] is how we access the second capture group, which results in the String value "32".

Regexes with named captures have match result record with the declared names as keys, and all values are of declared types

  • For instance, in example 4 above, the regex has type Regex<{name: String, age: Number}>, and so match("Name: Jane, Age: 32", re`Name: (?<name>\w+), Age: (?<age:Number>\d+)`).age is how we access the capture group named age, resulting in the Number value 32.
  • Moreover, notice that the capture group name has no declared type, so its type defaults to String.

See also

Functions

  • hasMatch: Checks whether a string matches the structure specified by a regex or not.
  • regexMatches: Gets the list of all substring matches of a given regex.

Types

See the regular expression guide.