regex
regex(text: String) : Regex<{}>
Converts text into a regular expression.
If text is not a valid regular expression, the query terminates with an error.
The regex(text) function is particularly useful when the regular expression is passed in to the query or if it is
dynamically computed by the query. For example:
@query
query(subIfaceIndex: String) =
foreach device in network.devices
foreach interface in device.interfaces
let isInteresting = hasMatch(interface.name, regex("eth.*/" + subIfaceIndex))
select { deviceName: device.name, isInteresting }
In contrast, the re syntax can only be used when the regular expression can be statically embedded in the query
source code.
Regular expressions created with this function do not capture any data, even if they have capture groups.
Examples
| Example | Result |
|---|---|
regex("[a-z][0-9]") | A valid regex matching a single lower case letter and then a digit. |
regex("(?<word>\\w+)") | The valid regex re`(?<word>\w+)` . |
regex("(?<word>\\w+") | Will throw an error, since the capture group is not closed: There's a missing ) at the end. |
regexMatches("2024 or 1974", regex("(?<year:Number>\\d{4})")) | A list of two matches. |
Backslashes
Care must be taken when using the backslash character \ in strings passed to the regex function.
It may be escaped twice: Once when constructing the string, and once when converted to a regular expression.
Because of this, a \ will be interpreted as escaping the subsequent character if not escaped itself.
To use a backslash \, escape it with a second backslash \\.
(Backslashes in regex literals do not require double escaping.)
This behavior is best illustrated by an example:
foreach phrase in [" cat"]
select {
"Works as intended, using literal syntax": hasMatch(phrase, re`\scat`),
"Works as intended, using regex and escapes": hasMatch(phrase, regex("\\scat")),
"Whoops, forgot to escape the slashes": hasMatch(phrase, regex("\scat")),
"Another case where we need to escape slashes": hasMatch("\\", regex("\\\\")) == hasMatch("\\", re`\\`)
}
This query results in one row with values true, true, false, true. The first two have the same output,
but the third one is erroneous.
See also
Functions
- hasMatch: Checks whether a string matches the structure specified by a regex or not.