javascriptjsonregexrecursionreadfile

regex - multiple line and multiple content


I'm looking for a pattern that match with

    "changes": [
      "5.12.0",
      "5.14.0"
    ],
...
    "changes": [
      "1",
      "5.0.0",
      "5.10.1"
    ],
...
    "changes": [
      "4.4",
      "5.0.0",
      "5.10.1"
    ],

I'm no expert, I've tried maybe 40 or 50 different solutions, here's my last try:

/"changes": \[\s*("([0-9](.+))*"(,+))*\s*\],/

i try this one and it works, ty.

"changes": \[\s*("([0-9](.+))*"(,+)\s )+("([0-9](.+))*"\s)\],

Solution

  • I would do it in two steps:

    1. Search for the list of versions between the brackets after "changes":

      /"changes":\s*\[\s*([^\]]+)\s*\]/g : https://regex101.com/r/XHaxJ0/4

    2. For each match, you'll get the list of versions in the capturing group 1:

      "4.4",
            "5.0.0",
            "5.10.1"
      

      You can then extract each version with /[\d.]+/g : https://regex101.com/r/XHaxJ0/2

    The Javascript code:

    const input = `    "changes": [
          "5.12.0",
          "5.14.0"
        ],
    ...
        "changes": [
          "1",
          "5.0.0",
          "5.10.1"
        ],
    ...
        "changes": [
          "4.4",
          "5.0.0",
          "5.10.1"
        ],`;
    
    const regexChangesContent = /"changes":\s*\[\s*([^\]]+)\s*\]/g;
    const regexVersion = /[\d.]+/g;
    
    // To fill with the found versions in the changes arrays.
    let versions = [];
    
    let matchChangesContent,
        matchVersion;
    
    while ((matchChangesContent = regexChangesContent.exec(input)) !== null) {
      while ((matchVersion = regexVersion.exec(matchChangesContent[1])) != null) {
        versions.push(matchVersion[0]);
      }
    }
    
    console.log(versions);

    EDIT since question has changed

    As you just want to delete the "changes" entries, I would do the following:

    const input = `    "changes": [
          "5.12.0",
          "5.14.0"
        ],
        "date": "01.01.2023",
        "changes": [
          "1",
          "5.0.0",
          "5.10.1"
        ],
        "property": "value",
        "should_stay": true,
        "changes": [
          "4.4",
          "5.0.0",
          "5.10.1"
        ],`;
    
    const regexChanges = /"changes":\s*\[\s*[^\]]+\s*\]\s*,/g;
    
    console.log(input.replace(regexChanges, ''));