1

I've scoured Stack Overflow for something just like this and can't seem to come up with a solution. I've got some text that looks like this:

command.Parameters.Add("@Id
command.Parameters.Add("@IsDeleted
command.Parameters.Add("@MasterRecordId
command.Parameters.Add("@Name
...

And I would like the text to end up like this:

command.Parameters.Add("@Id", acct.Id);
command.Parameters.Add("@IsDeleted", acct.IsDeleted);
command.Parameters.Add("@MasterRecordId", acct.MasterRecordId);
command.Parameters.Add("@Name", acct.Name);
...

As you can see, I essentially want to append the end of the line with: ", acct.<word between @ and second ">);

I'm trying this:

Find What: (?<=@).+?(?=\r) - This works, it finds the appropriate word.

Replace: \1", acct.\1); - This doesn't. It changes the line to (for Id):

command.Parameters.Add("@", acct.

Not sure what I'm doing wrong. I thought that \1 is supposed to be the "capture" from the "Find what" box, but it's not I guess?

B.Scar
  • 47
  • 5

2 Answers2

3

The \1 backreference will only work if you have a capturing group in your pattern:

(?<=@)(.+?)(?=\r)

If you're not using a capturing group, you should use $& instead of \1 as a backreference for the entire match. Additionally, parentheses in the replacement string need to be escaped. So, the replacement string should be:

$&", acct.$&\);

You might also want to use $ instead of the Lookahead (?=\r) in case the last line isn't followed by an EOL character.

Having said all that, I personally prefer to be more explicit/strict when doing regex substitution to avoid messing up other lines (i.e., false positives). So I would go with something like this:

Find: (\bcommand\.Parameters\.Add\("@)(\w+)$

Replace: \1\2", acct.\2\);

Note that \w will only match word characters, which is likely the desired behavior here. Feel free to replace it with a character class if you think your identifiers might have other characters.

  • Thanks, that did the trick! And thanks for the explanations, I only need to do something like this once in a great while and I always have a difficult time because the cheat sheets I've found don't go in depth enough. – B.Scar May 19 '22 at 17:02
1

You could also omit the lookbehind, and match the @ and then use \K to clear the current match buffer.

Then you can match the rest of the line using .+

Note that you don't have to make the quantifier non greedy .*? as you are matching the rest of the line.

In the replacement, use the full match using $0

See a regex demo for the matches:

Find what:

@\K.+

Replace with:

$0", acct.$0\)

enter image description here


If there must be a newline to the right, you might also write the pattern as one of:

@\K.+(?=\r)
@\K.+(?=\R)
The fourth bird
  • 154,723
  • 16
  • 55
  • 70