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?
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.
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.
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]+", "")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With