In json I need to replace all field names which contains hyphen with underscore, I wanna do it using regex groups. Here is my regex which I created so far:
/ "[a-zA-Z0-9] (-){1}[a-zA-Z0-9] ": / gm
It matches only field names which contains single hyphen, but I would like to match all fields which contains at least one hyphen and later capture each hyphen in group to replace it with under score.
Here is my test json and link to the regex101 sample: https://regex101.com/r/mnxrNj/1
{
"min-position": 3,
"has-more-items": false,
"items-html": "Bike",
"new-latent-count": 5,
"data": {
"length": 21,
"text": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
},
"numerical-Array": [
20,
30,
32,
24,
29
],
"String-Array": [
"Oxygen",
"Carbon",
"Oxygen",
"Nitrogen"
],
"multiple-Types-Array": 5,
"objArray": [
{
"class": "lower",
"age": 2
},
{
"class": "middle",
"age": 0
},
{
"class": "lower",
"age": 5
},
{
"class": "lower",
"age": 6
},
{
"class": "upper",
"age": 1
}
]
}
[1]: https://regex101.com/r/mnxrNj/1
CodePudding user response:
You can use
-(?=[^\"]*\"\s*:)
See the regex demo. Details:
-
- a hyphen(?=[\w-]*\"\s*:)
- a positive lookahead that matches a location that is immediately followed with[^\"]*
- zero or more chars other than"
\"
- a double quote\s*
- zero or more whitespaces:
- a colon.