Reputation: 569
I need to find if there are dots in the string in a row. For example
df...fd
This is not valid. But this
d.f.d.d
Is. I am not so strong with regulars expression, does anyone has an idea how to do this? In scala.
Upvotes: 0
Views: 1136
Reputation: 13922
A general-purpose solution that works not only on Strings, but on other collection types, is to use the sliding
method. It basically slides a fixed-size window over the collection, returning an iterator of those windows.
// string example
val s = "df..fd"
s.sliding(2) contains ".."
// list example
val list = List(1,2,3,4,5,6,2,3,7)
list.sliding(3) contains List(6,2,3)
Upvotes: 3
Reputation: 627536
I'd say contains
is really the best way to check something like 2 consecutive known characters. If you insist on a regex, here is a sample code (remember that you need to double-escape the dot to match a literal dot):
val pattern = "\\.{2}".r
val str = "df..d"
println(pattern findFirstIn str)
val pattern2 = "\\.{2}".r
val str2 = "df.f.d"
println(pattern2 findFirstIn str2)
println("df...fd - Офелия".contains(".."))
println("df.f.fd - Офелия".contains(".."))
Output:
Some(..)
None
true
false
Upvotes: 2