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
| Example | text | regex | The type of regex | The 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 as1. - 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 theStringvalue"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 somatch("Name: Jane, Age: 32", re`Name: (?<name>\w+), Age: (?<age:Number>\d+)`).ageis how we access the capture group namedage, resulting in theNumbervalue32. - Moreover, notice that the capture group
namehas no declared type, so its type defaults toString.
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.