Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my Regex.Replace string contain the replacement value twice?

Tags:

c#

.net

regex

I have the following string: aWesdE, which I want to convert to http://myserver.com/aWesdE.jpg using Regex.Replace(string, string, string, RegexOptions)

Currently, I use this code:

string input = "aWesdE";
string match = "(.*)";
string replacement = "http://myserver.com/$1.jpg";
string output = Regex.Replace(input, match, replacement,
          RegexOptions.IgnoreCase | RegexOptions.Singleline);

The result is that output is ending up as: http://myserver.com/aWesdE.jpghttp://myserver.com/.jpg

So, the replacement value shows up correctly, and then appears to be appended again - very strange. What's going on here?

like image 260
Dan Avatar asked Nov 22 '14 19:11

Dan


People also ask

How do you replace all occurrences of a regex pattern in a string?

sub() method will replace all pattern occurrences in the target string. By setting the count=1 inside a re. sub() we can replace only the first occurrence of a pattern in the target string with another string. Set the count value to the number of replacements you want to perform.

Does string replace take regex?

The Regex. Replace(String, MatchEvaluator, Int32, Int32) method is useful for replacing a regular expression match if any of the following conditions is true: The replacement string cannot readily be specified by a regular expression replacement pattern.

How do you replace special characters in regex?

If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")


1 Answers

There are actually 2 matches in your Regex. You defined your match like this:

string match = "(.*)";

It means match zero or more characters, so you have 2 matches - empty string and your text. In order to fix it change the pattern to

string match = "(.+)";

It means match one or more characters - in that case you will only get a single match

like image 177
dotnetom Avatar answered Sep 22 '22 02:09

dotnetom