【问题标题】:How to write a regular expression to condense folder path name change?如何编写正则表达式来压缩文件夹路径名称更改?
【发布时间】:2021-06-23 06:52:13
【问题描述】:

我正在尝试为 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"

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

【问题讨论】:

    标签: javascript regex path filenames


    【解决方案1】:

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

    匹配 {.*? => ([^}]+?)} 并替换为 $1

    来自 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.

    【讨论】:

    • 如果只有一个匹配项,那将起作用,但如果有多个匹配项呢?例如F{a => i}leT{b => e}st.d{c => l}l"
    • @aubreyquinn 正如您在 regex101 示例中看到的那样,它工作得很好 ;) 只需确保设置全局标志 (g)
    • 添加了 JS sn-p 来说明 :)
    猜你喜欢
    • 2017-02-13
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 2018-08-21
    相关资源
    最近更新 更多