Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic scala way of finding, if a given string contains a given substring?

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

like image 584
Karel Bílek Avatar asked Apr 12 '12 15:04

Karel Bílek


People also ask

How do you check if a string contains a substring in Scala?

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.

How do you know if a substring contains?

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.

How do you check if a character is present in a string in Scala?

string. matches("\\*+") will tell you if the string contains characters other than * .

Is substring a Scala?

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.


2 Answers

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 
like image 151
Rex Kerr Avatar answered Nov 01 '22 23:11

Rex Kerr


Although answered I thought I would also offer this regex style

scala> "I have a needle in my haystack" matches ".*needle.*" res10: Boolean = true 
like image 20
Neil Chambers Avatar answered Nov 02 '22 01:11

Neil Chambers