...

/

Finding Patterns in Strings

Finding Patterns in Strings

In the following lesson, you will be introduced to regular expressions and learn how to find patterns in a string in Scala.

Problem

A string is just a sequence of characters. Let’s say we want to find a particular sequence of characters in a string; we want to find a pattern. That pattern can be anything from a sequence of numbers to a sequence of characters and everything in between.

Solution

To understand the solution to this problem, we need to first go over regular expressions.

Regular Expressions

In computing, a regular expression is defined as “a sequence of symbols and characters expressing a string or pattern to be searched for within a longer string”.

For us to be able to let the compiler know which regular expression we want it to find, we need to first learn how to write a regular expression.

Writing Regular Expressions

Writing regular expressions is all about syntax. Once you know the syntax, it’s quite easy.

  • The * symbol is used to represent the repetition of the character preceding it. It basically tells us that “the character before me can exist 0 or more times”

The regular expression above is representing the patterns ac, abc, abbc, abbbc, etc. The character ‘b’ can be present from 0 times to an infinite number of times.

  • The + symbol is also used to represent the repetition of the character preceding it. However, unlike *, the character must be present at least once.

The regular expression above is representing the patterns abc, abbc, abbbc, etc. The character ‘b’ can be present from 1 time to an infinite number of times.

  • If you want to specify the number of times a character is being repeated, we can use curly brackets {} along with the number of repetitions we want in the pattern.

The regular expression above is representing the pattern abbc.

We can ...