Julia中字符串中正则表达式的匹配——match()和eachmatch()方法
match()
是 julia 中的一个内置函数,用于在指定字符串s中搜索给定正则表达式r的第一个匹配项,然后返回包含匹配项的 RegexMatch 对象,如果匹配失败则返回任何内容。
Syntax:
match(r::Regex, s::AbstractString, idx::Integer)
Parameters:
- r::Regex: Specified regular expression.
- s::AbstractString: Specified string.
- idx::Integer: It specifies the point from which the searching get started.
Returns: It returns a RegexMatch object containing the match or nothing if the match failed.
例子:
# Julia program to illustrate
# the use of match() method
# Getting a RegexMatch object containing
# the match or nothing if the match failed.
R = r"G(.)G"
println(match(R, "GFG"))
println(match(R, "Geeks"))
println(match(R, "gfgGfG"))
println(match(R, "GFG", 1))
println(match(R, "GFG", 2))
输出:
RegexMatch("GFG", 1="F")
nothing
RegexMatch("GfG", 1="f")
RegexMatch("GFG", 1="F")
nothing
每个匹配()
eachmatch()
是 julia 中的内置函数,用于在指定字符串s中搜索给定正则表达式r的所有匹配项,然后返回匹配项的迭代器。如果重叠为真,则允许匹配序列与原始字符串中的索引重叠,否则它们必须来自不同的字符范围。
Syntax:
eachmatch(r::Regex, s::AbstractString; overlap::Bool)
Parameters:
- r::Regex: Specified regular expression.
- s::AbstractString: Specified string.
- overlap::Bool: Specified overlap boolean value.
Returns: It returns a iterator over the matches.
例子:
# Julia program to illustrate
# the use of eachmatch() method
# Getting a iterator over the matches
R = r"G(.)G"
println(eachmatch(R, "GFG"))
println(eachmatch(R, "GeeksforGeeks"))
println(eachmatch(R, "Geeks"))
println(eachmatch(R, "GFG", overlap = true))
println(collect(eachmatch(R, "GFGGfGGeekGeeks", overlap = true)))
输出: