Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6557125
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T13:02:03+00:00 2026-05-25T13:02:03+00:00

With Scala’s pattern matching I would like to confirm not only that two String

  • 0

With Scala’s pattern matching I would like to confirm not only that two Strings are equal but for example, whether a String starts with, ends, or is contained in another etc.

I experimented with case classes and extractor objects, neither giving me a concise solution. So the solution I came up with looks like the following:

class StrMatches(private val str: Option[String]) {

  def ^(prefix: String) = str.exists(_.startsWith(prefix))

  def §(suffix: String) = str.exists(_.endsWith(suffix))

  def %(infix: String) = str.exists(_.contains(infix))

  def ~(approx: String) = str.exists(_.equalsIgnoreCase(approx))

  def /(regex: scala.util.matching.Regex) = str.collect({ case regex() => true }).isDefined

  def °(len: Int) = str.exists(_.length == len)

  def °°(len: (Int, Int)) = str.exists(a => a.length >= len._1 && a.length <= len._2)

  def `\\s*` = str.exists(_.trim.isEmpty)

  override def toString = str.mkString

}

object StrMatches {

  implicit def apply(x: Str) = new StrMatches(x)

  def unapply(x: StrMatches) = x.str

  implicit def unwrap(x: StrMatches) = x.toString

}

A client using the StrMatches class could look like the following:

object TestApp extends App {
  val str = "foobar"
  val strMatches = StrMatches(str)
  if (strMatches ^ "foo") {
    println(strMatches)
  }
  if (strMatches § "bar") {
    println(strMatches)
  }
  if (strMatches % "ob") {
    println(strMatches)
  }
}

As opposed to writing:

object TestApp extends App {
  val str: String = null // Just as an illustration for Scala interfacing Java.
  if (str != null) {
    if (str.startsWith("foo")) {
      println(str)
    }
    if (strMatches.endsWith("bar")) {
      println(str)
    }
    if (strMatches.contains("ob")) {
      println(strMatches)
    }
  }
}

With what kind of solutions would you come up with?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T13:02:04+00:00Added an answer on May 25, 2026 at 1:02 pm

    You could use regular expressions. Then you could use pattern matching (which I think was the original intent of your question):

    object TestApp extends App {
        val str = "foobar"
    
        val StartsWithFooRE = """^foo.*""".r
        val EndsWithBarRE = """.*bar$""".r
        val ContainsBoRE = """.*bo.*""".r
    
        str match {
            case StartsWithFooRE() => println(str)
            case EndsWithBarRE() => println(str)
            case ContainsBoRE() => println(str)
            case _ =>
        }
    }
    

    To make this more convenient, you could define an object with factory methods to construct the regular expressions. However, due to how pattern matching works, you’ll still have to define the expressions outside of the match:

    import scala.util.matching.Regex
    
    object RegexFactory {
        def startsWith(str: String) = new Regex("^%s.*" format str)
        def endsWith(str: String) = new Regex(".*%s$" format str)
        def contains(str: String) = new Regex(".*%s.*" format str)
    }
    
    
    object TestApp extends App {    
        val str = "foobar"
    
        import RegexFactory._
    
        val StartsWithFooRE = startsWith("foo")
        val EndsWithBarRE = endsWith("bar")
        val ContainsBoRE = contains("bo")
    
        str match {
            case StartsWithFooRE() => println(str)
            case EndsWithBarRE() => println(str)
            case ContainsBoRE() => println(str)
            case _ =>
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Scala Newbie alert: basically I'm trying to do something like this: where I pattern
Scala has both a mutable and an immutable Map , but it has only
Scala includes the continuations plugin now (yay), but must be enabled by passing -P:continuations:enable
Using Scala's command line REPL: def foo(x: Int): Unit = {} def foo(x: String):
In Scala, is it possible to get the string representation of a type at
(Scala 2.7.7:) I don't get used to 2d-Arrays. Arrays are mutable, but how do
In Scala 2.8.x, a new annotation ( @tailrec ) has been added that gives
scala> val s = 7.toBinayString <console>:7: error: value toBinayString is not a member of
Scala offers a method called stripMargin that removes the left-hand part of a multiline
In Scala, a class's primary constructor has no explicit body, but is defined implicitly

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.