Search code examples
javascriptregexphpstorm

regex in file over several lines replacing


I have a regex like this:

/ requires: \[.*("Instance.model.*?").*\] /gs

And I have data like this:

requires: [
    "Instance.model.a",
    "Instance.model.b",
    "Instance.model.c",
    "Other.mode.test",
    "Instance.model.d"
],

"Instance.model.e"

I want to delete all "Instance.model.?", in this file inside the requires, but the given regex only returns the last entry (d). How can I get this working in PhpStorm?


Solution

  • If supported, one option is to use an infinite quantifier in the lookbehind * or use a finite one {0,1000} when using Java for example.

    (?<=^requires: \[[^\[\]]{0,1000})"Instance\.model\.[a-z]",?\r?\n
    

    Explanation

    • (?<= Positive lookbehind, assert what is on the left is
      • ^requires: \[ Match requires from the start of the string followed by space
      • [^\[\]]{0,1000} Match 0 - 1000 times (this value you can change accordingly) any char except square brackets
    • ) Close the lookbehind
    • Instance\.model\. Match Instance.model.
    • [a-z]",?\r?\n Match a char a-z, optional comma and a newline

    Regex demo

    From the comments, the final pattern that worked for you (with the escaped dots)

    (?<=^ {0,8}requires: \[[^\[\]]{0,1000})"Instance\.model\.[a-zA-Z]*",?\r?\n?
    

    Regex demo