How to write a regular expression to condense folder path name change?

Viewed 72

I am trying to write a regular expression for JavaScript.

I have file names with folders and I need to consolidate them from the git changes. e.g. Input:

"9  1   {Folder_Old => Folder}/FileTest1.cs" 
"0  9   File{a => t}est2.cs" 
"-  -   F{a => i}leT{b => e}st.d{c => l}l" 
"9  1   {test/File.cs => test/File1.cs}" 

Expected Output per line:

"9  1   Folder/FileTest1.cs" 
"0  9   Filetest2.cs" 
"-  -   FileTest.dll" 
"9  1   test/File1.cs" 

Here is what I have tried so far:

var myentry = '9 9 {Folder_Old => Folder}/FileTest1.cs'

//find { A => B }

//replace { A => B } with B

let result = myentry.match(/{.+=>.+}/g);
console.log(result[0]) //"{Folder_Old => Folder}"

result[0] = result[0].replace('{', '')
result[0] = result[0].replace('}', '')
console.log(result[0]) //"Folder_Old => Folder"

var me = result[0].split(' ')
console.log(me) //["Folder_Old", "=>", "Folder"]

var he = myentry.replace(/{.+=>.+}/g, me[2])
console.log(he) //"9 9 Folder/FileTest1.cs"

How can I change my algorithm to cover all the cases?

1 Answers

If you match the replacements (inside {}), capturing the new value, you could just replace the match with the captured group.

Match {.*? => ([^}]+?)} and replace with $1.

Explanation from regex101:

{ matches the character { literally (case insensitive)
. matches any character (except for line terminators)
*? matches the previous token between zero and unlimited times, as few times as possible, expanding as needed (lazy)
 =>  matches the characters  =>  literally (case insensitive)
1st Capturing Group ([^}])
Match a single character not present in the list below [^}]
+? matches the previous token between one and unlimited times, as few times as possible, expanding as needed (lazy)
} matches the character } literally (case insensitive)
} matches the character } literally (case insensitive)

var samples = [
      '"9  1   {Folder_Old => Folder}/FileTest1.cs"',
      '"0  9   File{a => t}est2.cs"',
      '"-  -   F{a => i}leT{b => e}st.d{c => l}l"',
      '"9  1   {test/File.cs => test/File1.cs}"'
    ];

samples.forEach(s => console.log(s.replace(/{.*? => ([^}]+?)}/gmi, '$1')));

See it at regex101.

Related