【问题标题】:Regular expression to replace a value with one from the same line用同一行中的一个值替换一个值的正则表达式
【发布时间】:2022-01-16 13:55:02
【问题描述】:

我需要用每行逗号后面的值替换单词 'foo' - 例如'foo' 变为 'bar1'。输出应如下所示:this.load.image('bar1', bar1);

this.load.image('foo', bar1); 
this.load.image('foo', bar2); 
this.load.image('foo', bar3); 
...

如何用正则表达式做到这一点?

【问题讨论】:

    标签: regex visual-studio-code


    【解决方案1】:

    搜索:

    \('[^']+',\s*([^\)]+)\);\s*$
    

    替换

    ('$1', $1);
    

    根据文本编辑器,它可能是\1 而不是$1。我使用 sublime,所以我不确定使用的是哪种风格与代码。

    解释:

    \(        - Match (
    '[^']+',  - Match ', then all text until next ', next ' and the comma
    \s*       - Zero or more spaces
    ([^\)]+)  - Capture group everything up to the next ). the group is important
    \);\s*$   - Closing ); then any number of spaces and end of line.
    

    【讨论】:

    • 像魅力一样工作,非常感谢!保护我很多复制粘贴。 :)
    • 是的,没问题。正是出于这个原因,我一直在做这个正则表达式的变体。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    • 2017-08-22
    • 2020-01-21
    • 2022-01-17
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    相关资源
    最近更新 更多