Alessandro
Alessandro

Reputation: 39

Regex replace word after fixed string

I have a string like this

some text "myKey":myValue, some other text

I'd like to find all the occourrence of "mykey":myValue, and replace with

fixedText1 "myKey" fixedText2 : fixedText3 myValue fixedText4

I kwon the keys to change but not the values... (the keys are fixed)

briefly I'like to surround the key and the value with some html tag, only for a specific key.

Can you help me to find a regular ex that match?

I try to start from this example in javascript with 2 word without success

var re = /(\w+)\s(\w+)/;
var str = "zara ali";
var newstr = str.replace(re, "$2, $1");

Thanks a lot!

Alessandro

Upvotes: 0

Views: 111

Answers (2)

garyh
garyh

Reputation: 2852

"([^"]+)"[ :]+"?([\w+ ]+)"?

This regex will capture keys/values similar to

"myKey":myValue
"anotherKey": Another Value
"myNewKey": "New Value"
"numberKey" : 23

It assumes the key is surrounded by double-quotes but the value can be any word character A-Z0-9_ or space, optionally surrounded by double-quotes.

Then use $1 and $2 to insert into a new string as per your example

see demo here

Upvotes: 1

Federico Ginosa
Federico Ginosa

Reputation: 316

What do you think about awk?

cat test.txt | awk '{gsub(/"myKey/, "fixedText1\"myKey"); gsub(/:myValue/, "fixedText2 : fixedText3 myValue"); print'}

Upvotes: 0

Related Questions