Last post Aug 11, 2008 07:32 PM by Benners_J
Aug 11, 2008 05:08 PM|im1dermike|LINK
I'm trying to remove periods from strings that contain them.
Why does the following code return an empty string?
Regex.Replace("AA", ".", "")
Aug 11, 2008 07:07 PM|cv_vikram|LINK
Right, the Regex Replace in your case would do the following
Within a specified input string, replaces all strings that match a specified regular expression with a specified replacement string.
i.e. in the 'AA' string if there is '.' character it would be replaced by "" empty value.
Hope it cleared you.
Aug 11, 2008 07:13 PM|im1dermike|LINK
Sorry, that didn't clarify anything. As far as I understand it, the Replace function replaces the value you specify with the replacement you specify
only if they exist. ie. in my example where there is no period, no replacement should occur and the resulting value should be "AA". The actual value that results is an empty string which is what I don't understand.
Aug 11, 2008 07:13 PM|shados|LINK
The thing is that in regex, the period character means "any character" :) You probably want to escape it (backslash), or better yet, use String.Replace rather than Regex.Replace
Aug 11, 2008 07:22 PM|im1dermike|LINK
Ahhhh. That makes sense. The escape sequence "\." doesn't appear to work. When I try the Replace function, it doesn't like the empty literal I used.
string Item = e.Row.Cells.Text.Substring(0, 2).Replace('.','');
Do I have to use just a space character and then use Regex to replace it with an empty string? That's what I did and it appears to work.
Aug 11, 2008 07:32 PM|Benners_J|LINK
Single-quotes indicates that the literal value is a char. Double-quotes indicate that the literal value is a string. The error you are getting on Replace('.',''); is because you cannot have an empty char. If you use double-quotes, it will interpret it
as a string and it should work.
string Item = e.Row.Cells.Text.Substring(0, 2).Replace(".", "");