如何编写正则表达式来压缩文件夹路径名称的变化?

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

我正在尝试为 JavaScript 编写正则表达式。

我有带文件夹的文件名,我需要从 git 更改中合并它们。 例如 输入:

"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}" 

每行的预期输出:

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

这是我目前尝试过的方法:

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"

如何更改我的算法以涵盖所有情况?

如果匹配替换项(在 {} 内),捕获新值,您可以只用捕获的组替换匹配项。

匹配 {.*? => ([^}]+?)} 并替换为 </code>。</p> <p>来自 regex101 的解释:</p> <pre><code>{ 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, '')));

See it at regex101.