Regex direct capture group replace

Viewed 30

I am creating steps in Notepad++ to convert code from one form to another. For each line, I want to add "+@lin" at the beginning, then for each tab that follows add a "+@tab",then a single quote, then whatever remains, then another quote. Example:

Hi,
    adorable SO ppl!

should become

+@lin+'Hi'
+@lin+@tab+'adorable SO ppl!'

I have managed this in two steps:

First: replace ^(\t*)(.*)$ with \+@lin\1\+'\2'

Second: replace \t with \+@tab

I am wondering if this can be done better with a single replace. Can it be done?

One think I thought: Is it possible to use the asterisk of the \1 capture group to replace each \t instance with something else?

1 Answers

You might use a 2 capture groups with a conditional replacement.

Find what:

^\t(.*)|(.*)
  • ^ Start of string
  • \t(.*) match a tab and capture the rest of the string in group 1
  • | or
  • (.*) Capture the whole line in group 2

Replace with:

(?{2}\+@lin\+'\2':\+@lin\+@tab\+'\1')
  • (?{2} Check if capture group 2 exists
    • \+@lin\+'\2' If it does, use the replacement with the capture group 2 value
    • :\+@lin\+@tab\+'\1' else use the replacement with the capture group 1 value
  • ) Close

enter image description here

Related