match
match(r::Regex, s::AbstractString[, idx::Integer[, addopts]])
Search for the first match of the regular expression r
in s
and return a RegexMatch
object containing the match, or nothing if the match failed. The matching substring can be retrieved by accessing m.match
and the captured sequences can be retrieved by accessing m.captures
The optional idx
argument specifies an index at which to start the search.
Examples
-
Find the first match in a string:
julia> regex = r"(\d+)"; julia> text = "Julia version 1.6.0"; julia> m = match(regex, text) RegexMatch("1", 1="1")
This example searches for the first match of the regular expression
(\d+)
in the stringtext
. It returns aRegexMatch
objectm
containing the matched substring"1"
. The captured sequence can be accessed usingm.match
. -
Access captured sequences:
julia> regex = r"(\d+)-(\w+)"; julia> text = "Date: 2022-08-01"; julia> m = match(regex, text) RegexMatch("2022-01", 1="2022", 2="01")
In this example, the regular expression
(\d+)-(\w+)
captures the date in the formatyyyy-mm
. TheRegexMatch
objectm
contains the matched substring"2022-01"
. The captured sequences can be accessed usingm.captures
. -
Start the search from a specific index:
julia> regex = r"[aeiou]"; julia> text = "banana"; julia> m = match(regex, text, 3) RegexMatch("a", 1="a")
Here, the match starts from index 3 in the string
"banana"
. TheRegexMatch
objectm
contains the first vowel"a"
.
Common mistake example:
julia> regex = r"(\d+)";
julia> text = "No numbers here";
julia> m = match(regex, text)
nothing
In this example, the regular expression (\d+)
is used to search for numbers in a string that does not contain any. As a result, the match
function returns nothing
. Always ensure that the regular expression matches the expected pattern in the input string to avoid such situations.
See Also
eachmatch, ismatch, match, matchall,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.