简体   繁体   中英

Regular Expression matching filename in Scala

I'm creating files and would like to create a new filename if it already exists, much like the way OS X/windows does with the (1) appended.

I'm learning Scala at the moment and even though I'm sure there's a already a method out there; I'd very much like to know how to do this without it.

My aim is to see if the file exists via a private def doesFileExist(completeFilename: String) : Boolean = { logger.info("Checking if file already exists") Files.exists(Paths.get(completeFilename)) }

and then if it does I want to append the file name. Because I need to check if the filename has already been updated I thought it'd be easiest to regex and see if there was something like "/^[a-zA-Z0-9_-][\\\\d{1,2}][a-z0-9_\\\\.]{3,4}$/" Which I think will be suitable, I may be wrong, I haven't been able to test it. :)

I simply can't get it to compile no matter how many articles I read and so I'm not really sure how to fix it:

val RegexPattern = "/^[a-zA-Z0-9_-][\\d{1,2}][a-z0-9_\\.]{3,4}$/".r

  if (fileName.matches(RegexPattern)) {

  }

this clearly fails as it's expecting a string but I'm giving it Regex. I then tried a match...

  fileName match {
    case RegexPattern => println("Etf")
  }

but that's also incorrect. any help is appreciated, thank you.

Edit: A slightly different approach after finding an example online.

val pattern = "([0-9]+) ([A-Za-z]+)".r
  val pattern(count, fruit) = "100 Bananas"
  println(pattern)
  println(count)
  println(fruit)



  val RegexPattern = "(.+(?=\\/))(\\/)(.+(?=\\.))".r
  val RegexPattern(dir, delimeter, file) = "direct/ory/filename.ext"

  println(dir + " - " )

note, the bona example works fine, however mine does not. The regex is valid as tested.

Just in case this can help someone else:

I didn't realise that the regex needs to match the exact string I was comparing against.

my old pattern of val RegexPattern = "(.+(?=\\\\/))(\\\\/)(.+(?=\\\\.))".r was ignoring the extension on the end. I thought that, seeing as I didn't care about it, I wouldn't need to include it in the pattern. Foolishly expecting it to match the first and omit the rest.

This became clear when playing with a much simpler example using:

val x = "(\\w)(\\w)".r
  val x(c, s) = "an"
  println(c, s)

if you remove the 's' it complains, similary if you ass a char without updating the regex, it complains. Makes perfect sense in hindsight...

my working pattern with test is:

 val RegexPattern = "(.+(?=\\/))(\\/)(.+(?=\\.))(.*)".r
  val RegexPattern(dir, delimeter, file, ext) = "direct/ory/filename.ext"
  println(dir + " - "+ delimeter + " - " + file + " - " + ext)

Hope this helps someone else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM