1

I want to keep only the last term of a string separated by dots

Example:

My string is:

abc"val1.val2.val3.val4"zzz

Expected string after i use regex:

abc"val4"zzz

Which means i want the content from left-hand side which was separated with dot (.)

The most relevant I tried was

val json="""abc"val1.val2.val3.val4"zzz"""
val sortie="""(([A-Za-z0-9]*)\.([A-Za-z0-9]*){2,10})\.([A-Za-z0-9]*)""".r.replaceAllIn(json, a=>  a.group(3))

the result was:

abc".val4"zzz

Can you tell me if you have different solution for regex please?

Thanks

Valy Dia
  • 2,781
  • 2
  • 12
  • 32
jean-luc T
  • 51
  • 1
  • 7

2 Answers2

1

You may use

val s = """abc"val1.val2.val3.val4"zzz"""
val res = "(\\w+\")[^\"]*\\.([^\"]*\")".r replaceAllIn (s, "$1$2")
println(res)
// => abc"val4"zzz

See the Scala demo

Pattern details:

  • (\\w+\") - Group 1 capturing 1+ word chars and a "
  • [^\"]* - 0+ chars other than "
  • \\. - a dot
  • ([^\"]*\") - Group 2 capturing 0+ chars other than " and then a ".

The $1 is the backreference to the first group and $2 inserts the text inside Group 2.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 1
    Thanks for your help on that regex/eclipse question, too ;-) – GhostCat Dec 22 '16 at 08:07
  • Well,in real life, it's a big Json where some objects are prefixed with a domain name. For example: "bic3Reference":{"fr.laposte.colis.schema.pivot.common.parcel.ParcelReference":{"type":{"string":"c"},"ref":"b","key":{"string":"a"}}},"customerParcelReference":{"fr.laposte.colis.schema.pivot.common.parcel.CustomerParcelReference":{"ref":"CAB CY32"}} – jean-luc T Dec 22 '16 at 11:11
  • Then use approapriate tools, see [How to parse JSON in Scala using standard Scala classes?](http://stackoverflow.com/questions/4170949/how-to-parse-json-in-scala-using-standard-scala-classes) – Wiktor Stribiżew Dec 22 '16 at 11:18
0

Maybe without Regex at all:

scala> json.split("\"").map(_.split("\\.").last).mkString("\"")
res4: String = abc"val4"zzz

This assumes you want each "token" (separated by ") to become the last dot-separated inner token.

Tzach Zohar
  • 37,442
  • 3
  • 79
  • 85