BuddyJoe
BuddyJoe

Reputation: 71101

Regex - Replace Syntax - Backreferences

I'm trying to loop through all the lines of a file and for each line that contains a " I'm trying to replace the match with the line itself but with a " at the end too.

I'm using syntax like this from .NET/C#:

Regex re = new Regex("/\"/"); // without escaping would be /"/
re.Replace(" someAttr=\"some text here", "$0\"");

Upvotes: 1

Views: 1064

Answers (3)

lurkerguy
lurkerguy

Reputation: 64

This should work as well:

string line = "This is a string";

Regex re = new Regex("[\"].*");
re.Replace(line,"$0\"");

Upvotes: -1

Anirudha
Anirudha

Reputation: 32797

line="some text.d.sd..dsd.";    
Regex r=new Regex("\".*");
r.Replace(line,"$0\"");

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208465

Try the following:

Regex re = new Regex("\".*");
re.Replace(" someAttr=\"some text here", "$&\"");

First, you need to lose the slashes surrounding your regex.

According to this .NET regex reference page, $& is the reference to the entire match, not $0.

Also with your current method, you would just be replacing one double-quote with two consecutive double-quotes. Since you want to add the new double-quote to the end of the line you need to make your regex match to the end of the line, which is what the .* does.

Example: http://ideone.com/K5A7D

Upvotes: 2

Related Questions