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?

The
\1backreference will only work if you have a capturing group in your pattern:If you're not using a capturing group, you should use
$&instead of\1as a backreference for the entire match. Additionally, parentheses in the replacement string need to be escaped. So, the replacement string should be: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
\wwill 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.