Regular expressions: Difference between revisions

→‎{{header|Julia}}: shorten julia examples (just solve the problem at hand and don't try to document regular expressions in general)
(→‎{{header|Julia}}: shorten julia examples (just solve the problem at hand and don't try to document regular expressions in general))
Line 834:
 
=={{header|Julia}}==
{{trans|Perl}}
To check if a regex matches a string, use the ismatch function:
Julia implements Perl-compatible regular expressions (via the built-in [http://www.pcre.org/ PCRE library]). To test for a match:
<lang julia>
<lang julia> ismatch(r"^\s*(?:#|$)", = "notI am a commentstring")
if ismatch(r"string$", s)
false
println("'$s' ends with 'string'")
 
end</lang>
julia> ismatch(r"^\s*(?:#|$)", "# a comment")
To perform replacements:
true
<lang julia>s = "I am a string"
</lang>
s = replace(s, r" (a|an) ", " another ")</lang>
You can extract the following info from a RegexMatch object:
There are many [http://docs.julialang.org/en/latest/manual/strings/#regular-expressions other features] of Julia's regular-expression support, too numerous to list here.
 
the entire substring matched: m.match
the captured substrings as a tuple of strings: m.captures
the offset at which the whole match begins: m.offset
the offsets of the captured substrings as a vector: m.offsets
For when a capture doesn’t match, instead of a substring, m.captures contains nothing in that position, and m.offsets has a zero offset (recall that indices in Julia are 1-based, so a zero offset into a string is invalid). Here’s is a pair of somewhat contrived examples:
<lang julia>
julia> m = match(r"(a|b)(c)?(d)", "acd")
RegexMatch("acd", 1="a", 2="c", 3="d")
 
julia> m.match
"acd"
 
julia> m.captures
3-element Union(UTF8String,ASCIIString,Nothing) Array:
"a"
"c"
"d"
 
julia> m.offset
1
 
julia> m.offsets
3-element Int64 Array:
1
2
3
 
julia> m = match(r"(a|b)(c)?(d)", "ad")
RegexMatch("ad", 1="a", 2=nothing, 3="d")
 
julia> m.match
"ad"
 
julia> m.captures
3-element Union(UTF8String,ASCIIString,Nothing) Array:
"a"
nothing
"d"
 
julia> m.offset
1
 
julia> m.offsets
3-element Int64 Array:
1
0
2
</lang>
 
=={{header|Lua}}==
Anonymous user