Search code examples
regexreplacepcrefind-occurrences

Replace and/or remove first n occurrences of specific JSON key-value string from code file in PCRE Regex-supported Editors


I have many PHP code files, where I have to find and replace/remove specific JSON key-value string from those PHP files with any text editors that support PCRE-Regex.

The string I have to find and remove (replace with nothing, not even space), that spans multiple lines (and indentation is 2 spaces but it could be 4 spaces too) looks like:

{
  label: "Other",
  value: "Other",
},

How can I remove first (n) occurrences of above string with PCRE-regex in Sublime Text editor/Notepad++ , such that it doesn't make any unexpected changes elsewhere in the file?

I am not so good with Regex on multiple occurrences and greedy-nongreedy matches, so any help is appreciated, though, I did try this one, but it didn't work:

(.*?):\"Other\",

Solution

  • For the example data, you might use

    ^{\R\h{2,}label:\h+"Other",\R\h{2,}value:\h+"Other",\R},
    
    • ^{ Start of string and match {
    • \R\h{2,} Match a newline, 2 or more horizontal whitespace chars
    • label:\h+"Other", Match label: 1+ horizontal whitespace chars and "Other,"
    • \R\h{2,} Match a newline and 2 horizontal whitespace chars
    • value:\h+"Other",
    • \R}, Match an newline and },

    Replace with an empty string

    Regex demo

    If Other can be other values, you might use

    ^{\R\h{2,}label:\h+"[^"\\]*(?:\\.[^"\\]*)*",\R\h{2,}value:\h+"[^"\\]*(?:\\.[^"\\]*)*",\R},
    

    Regex demo