首页 > 解决方案 > How to duplicate regex search result within one line?

问题描述

I have a csv table following the scheme:

    "text1","text2",3
    "text5","text?",5
    "baa","foo",99
    ...

Which I need to transform to:

    "text1","text2","-text2-",3
    "text5","text?","-text?-",5
    "baa","foo","-foo-",99
    ...

I'm sorry but I have no idea how to duplicate a part of a line using a regex. I'm using VS Code find-replace engine. How could I do this?

标签: regexvisual-studio-code

解决方案


See regex101 demo.

Find: ^(\s*"[^"]*?","([^"]*?)",)

Replace: $1"-$2-",

Group 1: the first two values in each line, like "text1","text2",

Group 2: just the inner second value, like text2

Replace: Use Group 1 and then replicate Group 2 with surrounding "-Group2-"

Make sure you have this in your settings.json:

"search.usePCRE2": true,

推荐阅读