Home > Blockchain >  RegEx to match whole line after nth occurrence of a string
RegEx to match whole line after nth occurrence of a string

Time:05-28

Long time lurker, first time poster! Thanks to anyone in advance that can help.

I'm using Node.JS and Electron to make a little desktop app that manages the values in a game file (which is from a custom file type, basically a glorified INI file). With the idea of letting people customise the file in a nice UI as opposed to combing through hundreds of lines of code. Below is a sample from the file:

setting $Low
    prop $Config A_STRING_HERE "5, 10, 15, 20"

setting $Medium
    prop $Config A_STRING_HERE "10, 20, 40, 80"

setting $High
    prop $Config A_STRING_HERE "20, 40, 80, 160"

setting $VeryHigh
    prop $Config A_STRING_HERE "40, 80, 160, 320"

How would I go about matching, for example, the "setting $High" (3rd) occurrence containing "A_STRING_HERE" until the end of the line. I'm hoping to match just:
A_STRING_HERE "20, 40, 80, 160".

The values are dynamic and will change a lot, so matching the line with the values isn't necessarily an option.

  • \A_STRING_HERE. \g will match all the occurrences to the end of the line.
  • \A_STRING_HERE. \ will match the first occurrence to the end of the line.
  • \A_STRING_HERE. \?????? will match the 3rd occurrence to end of the line?

Thanks again and all the best!

CodePudding user response:

You can probably try this regex:

(?<=setting \$High\n\s*?prop \$Config )A_STRING_HERE.*

Explantion

  • (?<=) - Represents Image

    const regex = /(?<=setting \$High\n\s*?prop \$Config )A_STRING_HERE.*/g;
    
    // Alternative syntax using RegExp constructor
    // const regex = new RegExp('(?<=setting \\$High\\n\\s*?prop \\$Config )A_STRING_HERE.*', 'g')
    
    const str = `setting \$Low
        prop \$Config A_STRING_HERE "5, 10, 15, 20"
    setting \$Medium
        prop \$Config A_STRING_HERE "10, 20, 40, 80"
    setting \$High
        prop \$Config A_STRING_HERE "20, 40, 80, 160"
    setting \$VeryHigh
        prop \$Config A_STRING_HERE "40, 80, 160, 320"`;
    console.log(str.match(regex)[0]);

  • Related