Skip to content

Commit bb433e5

Browse files
Merge pull request #1359 from yadavan88/patter-match-string
Added sample for string interpolation matching
2 parents 6481d68 + 61c2084 commit bb433e5

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

scala-core-modules/scala-core/src/main/scala/com/baeldung/scala/patternmatching/PatternMatching.scala

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,17 @@ class PatternMatching {
9191
}
9292
}
9393

94+
def stringInterpolationMatching(toMatch: String): String = {
95+
toMatch match {
96+
case s"$firstName.$lastName@$domain.$extension" =>
97+
s"Hey ${firstName.capitalize} ${lastName.capitalize}, $domain.$extension is your email domain"
98+
case s"$day-$month-${year}T$time" => s"$month $day, $year"
99+
case s"$something($parenthesis)${_}" =>
100+
s"String between parenthesis: $parenthesis"
101+
case _ => "unknown pattern"
102+
}
103+
}
104+
94105
def optionsPatternMatching(option: Option[String]): String = {
95106
option match {
96107
case Some(value) => s"I'm not an empty option. Value $value"

scala-core-modules/scala-core/src/test/scala/com/baeldung/scala/patternmatching/PatternMatchingUnitTest.scala

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,46 @@ class PatternMatchingUnitTest {
155155
)
156156
}
157157

158+
@Test
159+
def whenEmailIsPassedWithComDomain_itShouldExtractParts(): Unit = {
160+
val result = new PatternMatching().stringInterpolationMatching(
161+
162+
)
163+
assertEquals("Hey James Kirk, starfleet.com is your email domain", result)
164+
}
165+
166+
@Test
167+
def whenEmailIsPassedWithCoInDomain_itShouldExtractParts(): Unit = {
168+
val result = new PatternMatching().stringInterpolationMatching(
169+
170+
)
171+
assertEquals("Hey James Kirk, starfleet.co.in is your email domain", result)
172+
}
173+
174+
@Test
175+
def whenDateTimeIsPassed_itShouldExtractDate(): Unit = {
176+
val result = new PatternMatching().stringInterpolationMatching(
177+
"01-April-2024T10:20:30"
178+
)
179+
assertEquals("April 01, 2024", result)
180+
}
181+
182+
@Test
183+
def whenStringIsPassed_itShouldExtractDataBetweenParenthesis(): Unit = {
184+
val result = new PatternMatching().stringInterpolationMatching(
185+
"Here is a (special) string"
186+
)
187+
assertEquals("String between parenthesis: special", result)
188+
}
189+
190+
@Test
191+
def whenUnknownDataIsPassed_itShouldReturnDefaultString(): Unit = {
192+
val result = new PatternMatching().stringInterpolationMatching(
193+
"something-unknown.unmatched"
194+
)
195+
assertEquals("unknown pattern", result)
196+
}
197+
158198
@Test
159199
def whenAFilledOptionIsPassed_ThenItShouldMatchTheSomeClause(): Unit = {
160200
val result =

0 commit comments

Comments
 (0)