help with regex, forward slash is skipped

677 views
Skip to first unread message

mc

unread,
May 17, 2013, 2:19:56 PM5/17/13
to scala...@googlegroups.com
Hello,
I'm trying to parse ftp URI using scala regular expressions. My URI looks like this:
val uri="ftp://user:pass...@server.com/directory/file.xml"

My regex looks like this (according to URI spec):
val Regex = """^ftp://(.*):(.*)@(.*)/(.*)""".r

However when I match by this regex URI is not parsed correctly:
uri match {
case Regex(userName,password,host,fileName) => ...
}

userName > user
password > password
host > server.com/directory
fileName > file.xml

I'm not sure why regex recognizes two forward slashes, but not one forward slash?
I'd like to get this back:

host > server.com
fileName > directory/file.xml

I'd appreciate any help in this matter.
Regards,

M

Ryan LeCompte

unread,
May 17, 2013, 2:23:28 PM5/17/13
to mc, scala-user
Your (.*) match is a little too greedy. This works:

scala> val R = """^ftp://(.*):(.*)@([^/]*)/(.*)""".r

scala> val R(name, password, host, file) = "ftp://user:pass...@server.com/directory/file.xml"
name: String = user
password: String = password
host: String = server.com
file: String = directory/file.xml




--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Som Snytt

unread,
May 17, 2013, 2:45:19 PM5/17/13
to Ryan LeCompte, mc, scala-user
You can also make it less greedy with the uncertainty operator, ?

Your example followed by the amendment:

scala> val uri="ftp://user:pass...@server.com/directory/file.xml"
uri: String = ftp://user:pass...@server.com/directory/file.xml

scala> val Regex = """^ftp://(.*):(.*)@(.*)/(.*)""".r
Regex: scala.util.matching.Regex = ^ftp://(.*):(.*)@(.*)/(.*)

scala> def f1 = uri match {
     | case Regex(userName,password,host,fileName) =>
     | fileName
     | }
f1: String

scala> f1
res0: String = file.xml

scala> val Regex2 = """^ftp://(.*):(.*)@(.*?)/(.*)""".r
Regex2: scala.util.matching.Regex = ^ftp://(.*):(.*)@(.*?)/(.*)

scala> def f2 = uri match {
     | case Regex2(userName,password,host,fileName) => fileName
     | }
f2: String

scala> f2
res1: String = directory/file.xml


Som Snytt

unread,
May 17, 2013, 2:47:31 PM5/17/13
to Ryan LeCompte, mc, scala-user
> Your (.*) match is a little too greedy.

And is there really such a thing as a little too greedy?

http://en.wikipedia.org/wiki/Greed


On Fri, May 17, 2013 at 11:23 AM, Ryan LeCompte <leco...@gmail.com> wrote:
Reply all
Reply to author
Forward
0 new messages