ankur gupta
ankur gupta

Reputation: 63

How to create a regex pattern for a specific pattern in json file in scala

I am trying to create a regex pattern to match a pattern in a Json file. Json file consists of the following kind of patterns - Examples

raw attribute can have any type of value between double quotes. I want to match all the patterns like this and replace it with “*” of the same length at that place.

I created a pattern “”"“raw”:(".*")""".r which works fine normally in editor but not in scala and it gives the complete string after raw.

How can I achieve this?

Upvotes: 1

Views: 404

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627469

Replacing a part of a matched pattern with asterisks of the same legnth as the pattern part, you may use a solution like

val s = "Text here, \"raw\": \"Remove\" and here"
val rx = "(\"raw\":\\s*\")([^\"]+)(\")".r
val res = rx.replaceAllIn(s, m => m.group(1) + ("*" * m.group(2).length) + m.group(3))
println( res ) // => Text here, "raw": "******" and here

The regex is

(\"raw\":\\s*\")([^\"]+)(\")
|___ Group1 ___||_ G2 _||G3|

It matches and captures into Group 1 (thanks to the capturing parentheses) "raw": and then 0+ whitespaces (with \s*), then captures into Group 2 any one or more chars other than ", and then captures into Group 3 a double quotation mark.

With the help of ReplaceAllIn, you can pass the match data into a lambda expression where you may manipulate the match before the replacement occurs. So, m is the match object, m.group(1) is Group 1 value, m.group(2).length is the length of Group 2 value and m.group(3) here holds the " char, Group 3 value.

Upvotes: 1

Related Questions