1

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”: “”\\""

  • “raw”: “true”

  • “raw”: “”’""

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?

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for informing me about this. I rarely post questions on stack overflow , therefore was not aware of it. I will take care of these things now onwards.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.