Scala Basics Tutorial (Eight): pattern matching, regular expression _scala

Source: Internet
Author: User
Tags finally block lowercase
Match use case class:

Case classes is used for pattern matching and case expression to specify the class. These are standard classes with special modifications: case. The following is a simple pattern that uses case class matching examples:

Object Test {
def main (args:array[string]) {
Val alice = new Person ("Alice", 25)
Val bob = new Person ("Bob", 32)
Val charlie = new Person ("Charlie", 32)
for (Person <-List (Alice, Bob, Charlie)) {
Person Match {
Case person ("Alice") => println ("Hi alice!")
Case person ("Bob") => println ("Hi bob!")
Case person (name, age) =>
println (' Age: ' + age + ' year, Name: "+ name +"? ")
}
}
}
Case class, empty one.
Case class Person (name:string, age:int)
}

When the above code is compiled and executed, it produces the following results:

C:/>scalac Test.scala
C:/>scala Test
Hi alice!
Hi bob!
Age:32 year, Name:charlie?
C:/>

Adding the CASE keyword allows the compiler to automatically add a number of useful features. Keyword suggests an expression that is associated with a pattern match.

First, the compiler automatically converts the parameters of the constructor to immutable fields (Vals). The Val keyword is optional. If you want to variable fields, use the var keyword. Therefore, the parameter columns of the constructor behave in a shorter form.

Second, the compiler automatically implements the Equals, Hashcode, and ToString method classes, which use the fields specified as constructor arguments. Therefore, you no longer need your own ToString method.

Finally, the body part of the person class disappears because there is no method that needs to be defined.

Scala supports the encapsulation of regular expressions through the scala.util.matching of the Regex class. Let's take a look at an example where we'll try to find the word from a statement in Scala:

Import Scala.util.matching.Regex
Object Test {
def main (args:array[string]) {
Val pattern = "Scala". R
Val str = "Scala is scalable and cool"
println (Pattern findfirstin str)
}
}

When the above code is compiled and executed, it produces the following results:

C:/>scalac Test.scala
C:/>scala Test
Some (Scala)
C:/>

We can create a string and call the R () method. In Scala, a string is implicitly converted to a richstring and called to obtain an instance of the regular expression. Find the first regular expression match, just call the Findfirstin () method. Rather than just finding the first time. If you want to find all occurrences of a matching word, you can use the Findallin () method and, in the case, use multiple Scala words in the target string, which returns all the matching collection words.

You can use the Mkstring () method to connect the resulting service, and you can use the pipe (|) Search Scala for small and medium sized and capital situations, use regular expression constructs instead or the R () method to create a pattern as follows:

Import Scala.util.matching.Regex
Object Test {
def main (args:array[string]) {
Val pattern = new Regex ("(s|s) Cala")
Val str = "Scala is scalable and cool"
println (Pattern Findallin str). mkstring (","))
}
}

When the above code is compiled and executed, it produces the following results:

C:/>scalac Test.scala
C:/>scala Test
Scala,scala
C:/>

If you want to replace the matching text, you can use Replacefirstin () to replace the first occurrence or Replaceallin () to replace all occurrences as follows:

Object Test {
def main (args:array[string]) {
Val pattern = "(S|s) Cala". R
Val str = "Scala is scalable and cool"
println (Pattern replacefirstin (str, "Java")
}
}

When the above code is compiled and executed, it produces the following results:

C:/>scalac Test.scala
C:/>scala Test
Java is scalable and cool
C:/>
To form a regular expression:

Scala inherits Java, which in turn inherits most of Perl's functionality, its regular expression syntax. Here are just a few examples that should be sufficient to illustrate:

The following is a table that lists the syntax for all regular expression metacharacters that can be used in Java:

Sub-expression

The

^

Matching Wardrobe

$

Match end of Line

.

Matches any single character except for line breaks. The M option also allows matching line breaks.

[...]

Matches any single character in parentheses.

[^...]

Matches any single character not in parentheses

\a

The beginning of the entire string

\z

End of entire string

\z

Eventually, the entire string is terminated except for the last line allowed.

re*

Match 0 or more occurrences of the preceding expression.

Re+

Match 1 or more previous items

Re?

Match 0 or 1 before the occurrence of the expression.

re{N}

Matches exactly the number of n-preceded expressions.

re{N,}

Matches n or multiple occurrences of the preceding expression.

re{N, m}

At least match N and show up in the front most m times.

A|b

Match A or B.

(RE)

Group regular expressions and remember the matching text.

(?: RE)

Group regular expressions without remembering matching text.

(?> re)

Match Standalone mode without reverse tracking.

\w

Matches the word character.

\w

Matches a non-word character.

\s

Match white space. equivalent to [f].

\s

Matches a non blank.

\d

Matches the number. equivalent to [0-9].

\d

Matches a non-numeric number.

\a

The string that matches the start.

\z

Matches the end of a string. If a newline character exists, it is only matched before wrapping.

\z

Matches the end of a string.

\g

Match point, last match end.

\ n

Reverse citation to capture group number "n"

\b

Matches the word boundary, in parentheses. Matches the backspace (0x08) bracket inside.

\b

Matches a non-word boundary.

\ n, \ t, etc.

Match line breaks, carriage returns, tabs, etc.

\q

Escape (Reference) all characters to \e

\e

Example of a \q regular expression starting with a tail reference:

Example

Describe

.

Match any character except for line breaks

[Rr]uby

Match "Ruby" or "Ruby"

Rub[ye]

Match "Ruby" or "Rube"

[Aeiou]

Match any one lowercase vowel

[0-9]

Match any number; with [0123456789]

[A-z]

Match any lowercase ASCII letter

[A-z]

Match any uppercase ASCII letter

[A-za-z0-9]

Match any of the above

[^aeiou]

Matches any lowercase character other than a vowel

[^0-9]

Matches any number other than the

\d

Match a number: [0-9]

\d

Match a non-number: [^0-9]

\s

Match a white space character: [F]

\s

Match non-blank: [^ f]

\w

Match one character: [a-za-z0-9_]

\w

Match a non-word character: [^a-za-z0-9_]

Ruby?

Match "rub" or "ruby": the Y is optional

ruby*

Match "rub" plus 0 or more Ys

ruby+

Match "rub" plus 1 or more YS

\D{3}

Match only 3 digits

\d{3,}

Match 3 or more digits

\d{3,5}

Match 3, 4, or 5 digits

\d\d+

No grouping: + Repeats \d

(\d\d) +/

Group: + Repeats \DD pair

([Rr]uby (,)?] +

Match "Ruby," "Ruby, Ruby, Ruby," and so on.

Note that each backslash appears two times above the string. This is because in Java and Scala a backslash is a string of escape characters instead of a normal character display string. So it's not. Need to write. \. Gets a backslash in the string. Check out the following example:

Import Scala.util.matching.Regex
Object Test {
def main (args:array[string]) {
Val pattern = new Regex ("abl[ae]\d+")
Val str = "Ablaw is able1 and cool"
println (Pattern Findallin str). mkstring (","))
}
}

When the above code is compiled and executed, it produces the following results:

C:/>scalac Test.scala
C:/>scala Test
Able1
C:/>

Scala's exceptions work like many other languages, such as Java exceptions. Instead of the normal return value, the method can terminate by throwing an exception. However, Scala does not actually check for exceptions.

When you want to handle an exception, you can use try{...} Catch{block, just as in Java in addition to catch blocks using matching to identify and handle exceptions. Throw an exception:

Throwing an exception looks similar to Java. Create an exception object and then use the Throw keyword to throw it:

throw new IllegalArgumentException
Catch exception:

In Scala, Try/catch captures any exception in a separate block and then uses the case block for pattern matching, as shown in the following illustration:

Import Java.io.FileReader
Import Java.io.FileNotFoundException
Import Java.io.IOException
Object Test {
def main (args:array[string]) {
try {
Val f = new FileReader ("Input.txt")
catch {
Case Ex:filenotfoundexception =>{
println ("Missing file Exception")
}
Case Ex:ioexception => {
println ("IO Exception")
}
}
}
}

When the above code is compiled and executed, it produces the following results:

C:/>scalac Test.scala
C:/>scala Test
Missing File exception
C:/>

The behavior of this try-catch expression is the same in other language processing exceptions. The body is an executor, and if it throws an exception, each catch clause attempts to catch it in turn. Finally clause:

If you want to know how to terminate execution that causes some code to be expressed, you can wrap an expression with a finally clause, and finally block when it will execute.

Import Java.io.FileReader
Import Java.io.FileNotFoundException
Import Java.io.IOException
Object Test {
def main (args:array[string]) {
try {
Val f = new FileReader ("Input.txt")
catch {
Case Ex:filenotfoundexception => {
println ("Missing file Exception")
}
Case Ex:ioexception => {
println ("IO Exception")
}
finally {
println ("exiting finally ...")
}
}
}

When the above code is compiled and executed, it produces the following results:

C:/>scalac Test.scala
C:/>scala Test
Missing File exception
Exiting finally ...
C:/>

The extractor is an object in Scala and has a method called non-application as its member. That is, the purpose of not applying a method is to match the value and take it apart. Typically, the extraction object also qualifies the two-way application build value, but this is not required.

The following example shows the Extractor object for the e-mail address:

Object Test {
def main (args:array[string]) {
println ("Apply method:" + Apply ("Zara", "gmail.com"));
println ("Unapply method:" + unapply ("Zara@gmail.com"));
println ("Unapply method:" + unapply ("Zara Ali"));
}
The injection method (optional)
def apply (user:string, domain:string) = {
User + "@" + domain
}
The extraction method (mandatory)
def unapply (str:string): option[(String, string)] = {
Val parts = str split "@"
if (parts.length = = 2) {
}else{
None
}
}
}

This object defines the apply and unapply methods. The Apply method has the same meaning: it was originally tested as an object that could be applied to the same way as the method applied in parentheses. Therefore, you can write the string "Zara@gmail.com" as Test ("Zara", "gmail.com").

The Unapply method makes the test Class A extractor and reverses the application's construction process. The application requires two strings and forms an e-mail address to locate them, the Unapply requires an e-mail address and may return two strings: the user and address of the domain name.

Unapply must also handle the case where the given string is not an e-mail address. That's why unapply returns an option-pair string. The result is either some (user domain) if the string Str uses a given email address of the user and the part of the domain, or none if Str is not an e-mail address. Here are some examples:

Unapply ("Zara@gmail.com") equals Some ("Zara", "gmail.com")
Unapply ("Zara Ali") equals None

Let's compile and run the above program, which will produce the following results:

C:/>scalac Test.scala
C:/>scala Test
Apply method:zara@gmail.com
Unapply Method:some ((zara,gmail.com))
Unapply Method:none
C:/>


From:http://www.yiibai.com/scala/scala_basic_syntax.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.