0

Good morning. I have a situation where I need to replace a keyword that may be anywhere on a line. The catch is that I need to add a comment line above. If the keyword is at the start of the line, I can do:

OldKeyword stuff stuff stuff

Replace: \nOldKeyword With: \nhashtag Comments\nNewKeyword

with extended search enabled. But if it's embedded, I need to take:

stuff stuff stuff OldKeyword stuff stuff stuff

And turn it into:

hashtag Comments

stuff stuff stuff NewKeyword stuff stuff stuff

retaining the code before the keyword.

Any help is Greatly appreciated.

I tried \n asterisk OldKeyword With: \n hashtag Comments\n asterisk NewKeyword

But it's as if that would be both extended and regular expression simultaneously.

1 Answer 1

1

You could use a capture group matching 0+ times any character except a newline, and then use that group in the replacement.

Instead of starting the match with a newline, you can use an anchor to also match the first line.

^(.*?)OldKeyword

In the replacement use:

hashtag Comments\n$1NewKeyword

See the replacement in the regex 101 demo


enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Nice link to regex 101. I did not know that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.