regex in scala interpreter

57 views
Skip to first unread message

Jose Francisco Gonzalez

unread,
Jul 14, 2011, 4:38:59 PM7/14/11
to scala-l...@googlegroups.com
I'm trying to use regex in a simple script (splitter.scala) using
the latest version of scala

>> Scala code runner version 2.9.0.1 -- Copyright 2002-2011, LAMP/EPFL

****BEGIN SCALA SCRIPT****
val data = "<a>aaaaa</a><b>bbbbbb</b><c>ccccccc</c>"

val p = "^<a>(.+)</a><b>(.+)</b><c>(.+)</c>$".r

val parts = p.findAllIn(data)
val aes = parts.group(1)
val bes = parts.group(2)
val ces = parts.group(3)

Console.println(aes)
****END SCALA SCRIPT****

executing it with

jfglez@Platea:~/Documentos/scala/m200$ scala splitter.scala

i get the following error:

java.lang.IllegalStateException: No match available
at java.util.regex.Matcher.start(Matcher.java:355)
at scala.util.matching.Regex$MatchIterator.start(Regex.scala:316)
at scala.util.matching.Regex$MatchData$class.group(Regex.scala:198)
at scala.util.matching.Regex$MatchIterator.group(Regex.scala:291)
at Main$$anon$1.<init>(splitter.scala:8)
at Main$.main(splitter.scala:1)
at Main.main(splitter.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
....

but executing line by line the above script on a scala console,
the "script" works.

where is the problem with the script?.

Some advice will be welcome

jfglez

Ken McDonald

unread,
Jul 14, 2011, 5:38:59 PM7/14/11
to scala-l...@googlegroups.com
Try taking out the "^" and "$" in the regex--they are affected by flags, I believe, which could be one (unlikely) source of variability.

If you will be using more complex regexes, you might want to check out http://kenmcdonald.github.com/rex .


Cheers,
Ken

Daniel Sobral

unread,
Jul 14, 2011, 11:37:42 PM7/14/11
to scala-l...@googlegroups.com
You *really* shouldn't call "group" on a MatchIterator, no matter what
the API says. The problem is that, at the time you call "group", no
matching was made yet! You haven't called "next" or anything to make
the match happen. If you type it on REPL, it works because "hasNext",
used to print the iterator, causes the match to be made.

You should iterate over the result of findAllIn to use it -- foreach,
flatMap, map...

--
Daniel C. Sobral

I travel to the future all the time.

Reply all
Reply to author
Forward
0 new messages