I have two strings in scala and I want to find out, if the bigger string (needle
) contains a smaller string (haystack
).
What I found is doing it with regexps and matches like this (from this question):
needle.r.pattern.matcher(haystack).matches
which is (1) grossly overcomplicated for such a simple problem, but more importantly, (2) doesn't work for me, because
"needle".r.pattern.matcher("Finding needle in haystack").matches
returns
Boolean = false
Use the contains() Function to Find Substring in Scala Here, we used the contains() function to find the substring in a string. This function returns a Boolean value, either true or false.
Java String contains() method It returns a boolean value true if the specified characters are substring of a given string and returns false otherwise. It can be directly used inside the if statement. The contains() method in Java returns true only if this string contains “s” else false.
string. matches("\\*+") will tell you if the string contains characters other than * .
The function substring() in Scala takes two parameters as an argument. First is the “int beginIndex” which is the starting index point of the substring function in Scala, and the second one is “int endIndex” which is the ending point of the substring() function in Scala.
If you want to do it with maximum efficiency, you may have to write it yourself (or find a good substring searching algorithm somewhere). If you just want it to work at all, then in Scala:
scala> "Finding needle in haystack" contains "needle" res0: Boolean = true scala> "Finding needle in haystack" indexOf "needle" res1: Int = 8
These are not regex searches. You aren't using the regex match correctly either (edit: because that code asks for an exact match to the whole string, not to find a matching substring), but that's a different issue. If you want a count of the number of matches, you can do something like
scala> "needle".r.findAllIn("Finding needle in haystack").length res2: Int = 1
Although answered I thought I would also offer this regex style
scala> "I have a needle in my haystack" matches ".*needle.*" res10: Boolean = true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With