Home > Back-end >  Replace occurrences in specific pattern
Replace occurrences in specific pattern

Time:01-31

I have a JSON file with text keys, for my code base, in the format

"abc.xyz": "plain text",
"abc.xyz.lmn": "plain text",
"abc.xyz.lmn.qrs.hij": "plain text",

Where xxx are keys of the format [a-zA-Z].[a-zA-Z] e.g. "app.feature.component.title" or similar.

I then have references to these all over the code base.

someComponent(title: "xyz.abc.ijk")

I am trying to substitute all the dots . in the keys with a dash - to get: xxx-xxx-xxx both in the code base and in the JSON, i.e. the surrounding structure might be different.

Something like this, but with the number xxx groups varying between keys:

\"([a-zA-Z] (\.)[a-zA-Z] ) 

I am using my editor (Xcode) so I think the regex flavour is ICU

CodePudding user response:

You could use look ahead assertion so to avoid matching letters that you still need to match for a next replacement. That look ahead assertion could also check that the sequence is ended by a double quote. This could be enough for checking that the target is quoted, without actually asserting that the sequence started with a quote:

Find: \.(?=[A-Za-z.] ")

Replace with: -

If two consecutive dots should be left unaltered, then:

Find: \b\.\b(?=[A-Za-z.] ")

CodePudding user response:

You could try to use below pattern

  • Search pattern: (?<="|\.)(\w ?)\.
  • Substitution value: $1-

Demo: https://regex101.com/r/PGnCG0/1

  • Related