What is the match_all() method in Euphoria?

Overview

The match_all() method in Euphoria searches a sequence called the haystack to find all of another sequence called the needle. The start position of this search can also be indicated.

On successful matching of all items of needle in the haystack, a value that has the index of the first matched character in the sequence is returned. If all of the needle is not matched in the haystack, we get back an empty sequence.

Syntax

match_all(needle,haystack, start)

Parameters

  • needle: This is a sequence that contains values that will be checked/searched in the haystack.

  • haystack: This is the sequence that will be searched through for a match.

  • start: This is the integer value which indicates where the search for a match is to start.

Return value

The match_all function returns a sequence.

This sequence contains an index of the first matched character in the needle. It means it returns the index of the point at which the match starts.

Note: If we provide the needle argument as an empty sequence the parser will raise an error and exit the program.

Code

Let's look at the code below:

--import the search module
include std/search.e
--declare some variables
sequence needle1, needle2, needle3, needle4
sequence result1, result2, result3, result4
--assign values to declared variables
needle1 = "first needle"
needle2 = "these are"
needle3 = "is the"
needle4 = {"sure","the","second","matches"}
--call the function match_all function
--checks for a match starting at index `13`.
result1 = match_all(needle1,"This is the first needle",13)
--no match is found
result2 = match_all(needle2,"This is the first")
--a match 'is the' is found at index 6
result3 = match_all(needle3,"This is the first")
--the whole haystack matches the needle; needle4
result4 = match_all(needle4,{"sure","the","second","matches"})
--display our output so far
print(1,result1)
puts(1,"\n")
print(1,result2)
puts(1,"\n")
print(1,result3)
puts(1,"\n")
print(1,result4)

Explanation

  • Line 2: We import the search.e inbuilt module which enables us to use the match_all() method.

  • Lines 5 and 6: We declare a group of variables for the needle and another for holding the results as a sequence.

  • Lines 9 to 12: We assign values to the declared group of needle variables.

  • Lines 16, 18, 21, and 24: We call the match_all() method and use it in different ways to explore the possible outcomes. The output is also assigned to the group of result variables declared previously.

  • Lines 28 to 34: The output of the match_all() method is printed to the screen.

Free Resources