1
val file_name="D:/folder1/folder2/filename.ext"    //filename
val reg_ex = """(.*?).(\\\\w*$)""".r  //regex pattern

 file_name match {
      case reg_ex(one , two) =>s"$two is extension"
      case _ => println(" file_reg_ex none")
    }

I want to extract file extension i.e."ext" from the above using scala regex , using match & case.

I am using above regex and it is going into not match case.

Any pointers to regex tutorials will be helpful.

2
  • What have you tried? Where are you stuck? Post some code that doesn't work and we can point out where it's going off track. Commented Aug 7, 2017 at 22:00
  • @jwvh I have updated the code , please check Commented Aug 7, 2017 at 22:05

1 Answer 1

8

A few minor adjustments.

val reg_ex = """.*\.(\w+)""".r

file_name match {
  case reg_ex(ext) =>s"$ext is extension"
  case _ => println("file_reg_ex none"); ""
}

Only one capture group needed. Ignore everything before the final dot, \. (escaped so it's a dot and not an "any char") and capture the rest.

The default, case _, should do more than println. It should return the same type as the match.

Sign up to request clarification or add additional context in comments.

3 Comments

that worked !! THanks a lot , can you point me to any regex tutorials, probably specific to scala will be much more better , that will be great.
1 - Glad I could help. 2 - The proper expression of gratitude, here on SO, is an up-vote and/or mark the answer as "accepted". 3 - I'm sure there are many fine regex tutorials on-line. I haven't used any recently so I don't have any recommendations.
+1 to fixing the case _ in the answer. Scala regex is java regex, but there are examples at scala-lang.org/api/current/scala/util/matching/Regex.html For parsing file paths, you really want a lib, not regexes. There are several libs.

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.