"World" ∈ "Hello, World!"LoadError: use occursin(needle, haystack) for string containment
April 9, 2023
In this beginner-friendly tutorial, we’ll demonstrate how to check if a string (String) contains a specific substring (SubString) in Julia.
For those familiar with Python, you might instinctively attempt to use in or ∈ in Julia to verify if a SubString is present in a String. However, these approaches won’t work.
In Julia, you need to use either occursin or contains:
Remember the order of the arguments in contains(haystack, needle) as haystack contains needle. For occursin(needle, haystack), recall the order as needle occursin haystack.
This naming pattern is fairly common in Julia.
In Julia, you can create a regular expression (Regex) by using the string literal macro syntax with the letter r, such as r"regex_pattern".
If you’re only interested in determining whether a match exists, use the isnothing function to check the return value of match.
More idiomatically, you can use the occursin or contains functions with Regex objects as well:
The Regex string literal macro supports adding flags at the end of the string.
To obtain the index of the first occurrence of a SubString within a String, you can use the findfirst function:
To find all the occurrences of a SubString within a String, you can use the findall function:
In this tutorial, we have explored various methods to determine if a string contains a specific substring in Julia.
With these tools in your toolbox, you should be well-equipped to handle string manipulation tasks in Julia, and hopefully with time, you’ll find that Julia’s built-in functions and idiomatic patterns make working with strings both efficient and enjoyable.