Home > Enterprise >  Regex to add extension in specific lines
Regex to add extension in specific lines

Time:11-03

I want to add a new path with the name of the last path from import with .cjs extension to every import which contains 'primereact'.

For example:

import { nanoid } from "nanoid";
import { Button } from "primereact/button";

Should be:

import { nanoid } from "nanoid";
import { Button } from "primereact/button/button.cjs";

I want to connect regex with js replace function

string.replace(//g, '');

I have a regex to find the line which contains import and primereact, but can't add necessary file with extension.

.*(import) .*(primereact) .*

CodePudding user response:

the following regex captures the last word in every input line which contains primereact:

(?<=(^|\n)import. ?primereact[^\/]*\/). ?(?=\";)

the resulting match of your example input would then be: button

using this match, we can add the necessary path information like in this pseudo code:

var regex = "(?<=(^|\n)import. ?primereact[^\/]*\/). ?(?=\";)";
foreach (var line in lines)
{
   var match = line.match(regex);
   if (match)
   {
      line = line.replace(regex, match.result   "/"   match.result   ".cjs");
   }
}

CodePudding user response:

const source = `import { nanoid } from "nanoid";
import { Button } from "primereact/button";
import { Butter } from "primereact/butter";`
const regex = /(\bimport\b.*?\bfrom  "primereact\/)([^"] )/g;
let result = source.replace(regex, (m, g1, g2) => {
  return g1   g2   '/'   g2   '.cjs'; 
});
console.log(result);

Output:

import { nanoid } from "nanoid";
import { Button } from "primereact/button/button.cjs";
import { Butter } from "primereact/butter/butter.cjs";

Explanation of regex:

  • (\bimport\b.*?\bfrom "primereact\/) -- capture group 1 using word boundaries \b to avoid false positives
  • ([^"] ) -- capture group 2 capturing everything up to double quote
  • the replace function composes the desired string from capture group g1 and g2

CodePudding user response:

You might use for example a pattern with capture groups, and use those groups in the replacement.

^(import\s {[^{}]*}\s from\s (["'])primereact\/)(.*?)\2

The pattern matches:

  • ^ Start of string
  • ( Capture group 1
    • import\s Match import, 1 whitespace chars
    • {[^{}]*} Match from {...}
    • \s from\s Match from between whitespace chars
    • (["']) Capture either " or ' in group 2
    • primereact\/ Match primereact/
  • ) Close group 1
  • (.*?) Capture group 3, match any char, as few as possible
  • \2 Match the same closing quote that was captured in group 2

Regex demo

const regex = /^(import\s {[^{}]*}\s from\s (["'])primereact\/)(.*?)\2/gm;
const str = `import { nanoid } from "nanoid";
import { Button } from "primereact/button";`;
console.log(str.replace(regex, `$1$3/$3.cjs$2`));

  • Related