1

In my scala program, I want to use a pattern match to test whether there is a valid .csv file in the input path. path ="\DAP\TestData\test01.csv" val regex=""".csv$""".r.unanchored

I tried to use the previous regex to match the string, it worked, but when it went to match pattern, it cannot work.

path ="\DAP\TestData\test01.csv"
val regex="""\.csv$""".r.unanchored    
path match {
  case regex(type) =>println(s"$type matched")
  case _ =>println("something else happeded")
}

I need to successfully print information like ".csv matched". Could anyone help me with this issue? I m really confused by this issue. Thanks

2 Answers 2

1

It's not clear which part of the path you want to capture and report. But in any case you'll probably want a capture group in the regex pattern.

val path = raw"\DAP\TestData\test01.csv"
val re = """(.*\.csv)$""".r.unanchored
path match {
  case re(typ) => println(s"$typ matched")   //"\DAP\TestData\test01.csv matched"
  case _       => println("something else happened")
}

You can also use the capture group to capture any one of many different target patterns.

val re = ".*\\.((?i:json|xml|csv))$".r
raw"\root\test31.XML" match {
  case re(ext) => println(s"$ext matched")   //"XML matched"
  case _       => println("something else happeded")
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can try it like this:

 val regex = """(\.csv)$""".r.unanchored

    path match {
      case regex(fileType) => println(s"$fileType matched")
      case _ => println("something else happeded")
    }

2 Comments

Thanks, Teena. while I have multiple regex for matching different types of files, like json, xml,csv. So I need to use the pattern to match those regex expressions in the pattern match code block. Is there a way to do this?
Hi, @kyandy, I've updated my comment. You just need to modify the regex, have a look.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.