eachmatch

eachmatch(r::Regex, s::AbstractString[, overlap::Bool=false])

Search for all matches of a the regular expression r in s and return a iterator over the matches. If overlap is true, the matching sequences are allowed to overlap indices in the original string, otherwise they must be from distinct character ranges.

Examples

  1. Find all matches in a string:

    julia> using Regex
    
    julia> regex = r"Julia";
    
    julia> text = "Julia is a high-level, high-performance programming language.";
    
    julia> matches = eachmatch(regex, text);
    
    julia> for match in matches
              println(match.match)
          end
    Julia

    This example uses the eachmatch function to find all occurrences of the regex pattern "Julia" in the given string text. It then iterates over the matches and prints the matched substring.

  2. Find overlapping matches in a string:

    julia> regex = r"a";
    
    julia> text = "banana";
    
    julia> matches = eachmatch(regex, text, true);
    
    julia> for match in matches
              println(match.match)
          end
    a
    a
    a

    Here, the eachmatch function is used to find all occurrences of the letter "a" in the string text, allowing overlapping matches. The matches are then printed using a loop.

  3. Access match information:

    julia> regex = r"\w+";
    
    julia> text = "Hello, Julia!";
    
    julia> matches = eachmatch(regex, text);
    
    julia> for match in matches
              println("Match: ", match.match)
              println("Index range: ", match.offsets)
              println("Matched substring: ", match.matched)
              println("------")
          end
    Match: Hello
    Index range: (1, 5)
    Matched substring: Hello
    ------
    Match: Julia
    Index range: (8, 12)
    Matched substring: Julia
    ------

    This example demonstrates how to access match information using the eachmatch function. It prints the matched substring, the index range where the match occurred, and the match itself.

Common mistake example:

julia> regex = r"[A-Z]+";
julia> text = "julia";
julia> matches = eachmatch(regex, text);
julia> length(collect(matches))
ERROR: MethodError: no method matching length(::Array{SubString{String},1})

In this example, the regex pattern [A-Z]+ is used to match uppercase letters in the string text. However, since there are no uppercase letters in text, the eachmatch function returns an empty iterator. Trying to find the length of the iterator (length(collect(matches))) results in an error. It's important to handle such cases and validate the results accordingly.

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.

*Required Field
Details

Checking you are not a robot: