0

Been scratching my head all day about this one!

Ok, so I have a string which contains the following:

?\"width=\"1\"height=\"1\"border=\"0\"style=\"display:none;\">');

I want to convert that string to the following:

?\"width=1height=1border=0style=\"display:none;\">');

I could theoretically just do a String.Replace on "\"1\"" etc. But this isn't really a viable option as the string could theoretically have any number within the expression.

I also thought about removing the string "\"", however there are other occurrences of this which I don't want to be replaced.

I have been attempting to use the Regex.Replace method as I believe this exists to solve problems along my lines. Here's what I've got:

chunkContents = Regex.Replace(chunkContents, "\".\"", ".");

Now that really messes things up (It replaces the correct elements, but with a full stop), but I think you can see what I am attempting to do with it. I am also worrying that this will only work for single numbers (\"1\" rather than \"11\").. So that led me into thinking about using the "*" or "+" expression rather than ".", however I foresaw the problem of this picking up all of the text inbetween the desired characters (which are dotted all over the place) whereas I obviously only want to replace the ones with numeric characters in between them.

Hope I've explained that clearly enough, will be happy to provide any extra info if needed :)

1
  • You only want to replace the \ from the width element and the border element and the style element? Commented Nov 29, 2013 at 12:33

2 Answers 2

3

Try this

var str = "?\"width=\"1\"height=\"1234\"border=\"0\"style=\"display:none;\">');";
str = Regex.Replace(str , "\"(\\d+)\"", "$1");

(\\d+) is a capturing group that looks for one or more digits and $1 references what the group captured.

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

1 Comment

Ah nice one mate, I now understand I should have been looking for backreferences. Works perfectly.
1

This works

String input = @"?\""width=\""1\""height=\""1\""border=\""0\""style=\""display:none;\"">');";

//replace the entire match of the regex with only what's captured (the number)
String result = Regex.Replace(input, @"\\""(\d+)\\""", match => match.Result("$1"));

//control string for excpected result
String shouldBe = @"?\""width=1height=1border=0style=\""display:none;\"">');";

//prints true
Console.WriteLine(result.Equals(shouldBe).ToString());

Comments

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.