Pattern Class - Unsuccessful Match - match

Can you give me example about pattern class which can not match? Exactly, I need unsuccessful match with Pattern class. How should I find it out?

You can use the following example to demonstrate the usage of Pattern class to match numbers only.
String NUMBER_PATTERN = "\\d+";
Pattern pattern = Pattern.compile(NUMBER_PATTERN);
System.out.println("False validation:: " + pattern.matcher("123a").matches());
System.out.println("True validation:: " + pattern.matcher("123").matches());

Related

Scala: using wildcard with Option in pattern matching for a case class with too many parameters

I have a pattern matching code. X is a case class with too many parameters. I just want to do some check for its 3rd,4th parameter, and would like to use wildcard for rest of them.
o match {
case Some(X(_,_, a,b, _*))) => // do something
case _ => // do something else
}
This doesn't seem to work for me. What is correct way of using wildcard here?

Use symbolic constant in actor receive block cases to match conditions

I want to use symbolic constant in actor receive block cases to match conditions.
val str1 = "This is just a demo string to match"
val date = OffsetDateTime.parse("some date")
def receive: Receive = {
case CaseClassA(**str1**, **date**) =>
sender() ! Some("data")
I want to do something like that :
case CaseClassA(**str1**, **date**)
But it does not consider the constants. I have to write it in the manner:
case CaseClassA("This is just a demo string to match", OffsetDateTime.parse("some date"))
Is there any way i can use symbolic constants?
Try surrounding str1 and data in backquotes (backticks) like so
case CaseClassA(`str1`, `date`) =>
According to SLS - 8.1.6 Stable Identifier Patterns:
To resolve the syntactic overlap with a variable pattern, a stable
identifier pattern may not be a simple name starting with a lower-case
letter. However, it is possible to enclose such a variable name in
backquotes; then it is treated as a stable identifier pattern

Find longest prefix that matches a certain condition in scala

I am trying to figure out a way to find out longest prefix of a string which matches a certain condition.
It is trivial to write a imperative method which does exactly that, but I am new to scala and wondering if there is an idiomatic scala (or functional) way to do that.
Keep iterating through longest prefixes (mystring.take(mystring.size),..mystring.take(1)
Apply a predicate on each of those substrings
If a prefix matches a predicate, break the loop and return the longest prefix.
For example, this:
def predicate(str: String): Boolean = ???
val longest_matching: Option[String] =
Iterator(mystring.size, 0, -1) // iterator of lengths
.map(mystring.take) // take string prefix
.find(predicate) // find first matching entry
longest_matching.fold {
println("No matching prefix")
} { prefix =>
println("Longest matching prefix: " + prefix)
}
You can take full advantage of the Scala standard library by using inits:
val longest_matching = mystring.inits.find(predicate)

Runtime exception in syntax like defining two vals with identical names

In some book I've got a code similar to this:
object ValVarsSamples extends App {
val pattern = "([ 0-9] +) ([ A-Za-z] +)". r // RegEx
val pattern( count, fruit) = "100 Bananas"
}
This is supposed to be a trick, it should like defining same names for two vals, but it is not.
So, this fails with an exception.
The question: what this might be about? (what's that supposed to be?) and why it does not work?
--
As I understand first: val pattern - refers to RegEx constructor function.. And in second val we are trying to pass the params using such a syntax? just putting a string
This is an extractor:
val pattern( count, fruit) = "100 Bananas"
This code is equivalent
val res = pattern.unapplySeq("100 Bananas")
count = res.get(0)
fruit = res.get(1)
The problem is your regex doesn't match, you should change it to:
val pattern = "([ 0-9]+) ([ A-Za-z]+)". r
The space before + in [ A-Za-z] + means you are matching a single character in the class [ A-Za-z] and then at least one space character. You have the same issue with [ 0-9] +.
Scala regexes define an extractor, which returns a sequence of matching groups in the regular expression. Your regex defines two groups so if the match succeeds the sequence will contain two elements.

Scala pattern matching against URLs

Is there a Scala library/example that will parse a URL/URI into a case class structure for pattern matching?
Here's an extractor that will get some parts out of a URL for you:
object UrlyBurd {
def unapply(in: java.net.URL) = Some((
in.getProtocol,
in.getHost,
in.getPort,
in.getPath
))
}
val u = new java.net.URL("http://www.google.com/")
u match {
case UrlyBurd(protocol, host, port, path) =>
protocol +
"://" + host +
(if (port == -1) "" else ":" + port) +
path
}
I would suggest to use the facility provided by extractors for regular expressions.
For instance:
val URL = """(http|ftp)://(.*)\.([a-z]+)""".r
def splitURL(url : String) = url match {
case URL(protocol, domain, tld) => println((protocol, domain, tld))
}
splitURL("http://www.google.com") // prints (http,www.google,com)
Some explanations:
The .r method on strings (actually, on StringLikes) turns them into an instance of Regex.
Regexes define an unapplySeq method, which allows them to be used as extractors in pattern-matching (note that you have to give them a name that starts with a capital letter for this to work).
The values that are going to be passed into the binders you use in the pattern are defined by the groups (...) in the regular expression.
You can use java's URL which can parse an URL for its different components and is completely Scala compatible.
The following library can help you parse URIs into an instance of a case class. (Disclaimer: it is my own library)
https://github.com/theon/scala-uri
You parse like so:
import com.github.theon.uri.Uri._
val uri:Uri = "http://example.com?one=1&two=2"
It provides a DSL for building URLs with query strings:
val uri = "http://example.com" ? ("one" -> 1) & ("two" -> 2)