Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a String fully matches a Regex in Scala?

Tags:

regex

scala

Assume I have a Regex pattern I want to match many Strings to.

val Digit = """\d""".r 

I just want to check whether a given String fully matches the Regex. What is a good and idiomatic way to do this in Scala?

I know that I can pattern match on Regexes, but this is syntactically not very pleasing in this case, because I have no groups to extract:

scala> "5" match { case Digit() => true case _ => false } res4: Boolean = true 

Or I could fall back to the underlying Java pattern:

scala> Digit.pattern.matcher("5").matches res6: Boolean = true 

which is not elegant, either.

Is there a better solution?

like image 254
mkneissl Avatar asked Jun 11 '10 09:06

mkneissl


People also ask

How do you check if a string matches a regex in Scala?

The matches() method is used to check if the string stated matches the specified regular expression in the argument or not. Return Type: It returns true if the string matches the regular expression else it returns false.

How do I find all matches in regex?

The method str. match(regexp) finds matches for regexp in the string str . If the regexp has flag g , then it returns an array of all matches as strings, without capturing groups and other details. If there are no matches, no matter if there's flag g or not, null is returned.

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.


1 Answers

Answering my own question I'll use the "pimp my library pattern"

object RegexUtils {   implicit class RichRegex(val underlying: Regex) extends AnyVal {     def matches(s: String) = underlying.pattern.matcher(s).matches   } } 

and use it like this

import RegexUtils._ val Digit = """\d""".r if (Digit matches "5") println("match") else println("no match") 

unless someone comes up with a better (standard) solution.

Notes

  • I didn't pimp String to limit the scope of potential side effects.

  • unapplySeq does not read very well in that context.

like image 167
mkneissl Avatar answered Sep 28 '22 07:09

mkneissl