Scala pattern matching for DCRs in TeamSite

Posted: 20 January 2013 in CSSDK, Java, Scala

Here’s a quick example on how to do a regular expression matching in scala for a DCR

scala> val regexString="templatedata/category/type/data/(.*?)/(.*)"

regexString: java.lang.String = templatedata/category/type/data/(.*?)/(.*)

scala> val regex=regexString.r
regex: scala.util.matching.Regex = templatedata/category/type/data/(.*?)/(.*)

scala> val regex(language,file)=”templatedata/category/type/data/en_gb/mydcr”

language: String = en_gb
file: String = mydcr

scala> println(language)
en_gb

scala> println(file)
mydcr

If the file does not match the pattern, this happens:

scala> val regex(language,file)=”templatedata/category/type/data/en_gb”
scala.MatchError: templatedata/category/type/data/en_gb (of class java.lang.String)
at .<init>(<console>:11)
at .<clinit>(<console>)
at .<init>(<console>:11)
at .<clinit>(<console>)
at $print(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:704)
at scala.tools.nsc.interpreter.IMain$Request$$anonfun$14.apply(IMain.scala:920)
at scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:43)
at scala.tools.nsc.io.package$$anon$2.run(package.scala:25)
at java.lang.Thread.run(Thread.java:679)

In order to avoid the exception, a quick check that it does match is in order:

scala> “templatedata/category/type/data/en_gb”.matches(regex.pattern.toString)
res4: Boolean = false

scala> “templatedata/category/type/data/en_gb/mydcr”.matches(regex.pattern.toString)
res5: Boolean = true

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s