Regular Expression Help

Wjousts

Newcomer
Joined
Sep 24, 2003
Messages
6
I want to match and replace a character sequence in the middle of a string, but the same sequence could appear at the begining or the end of the string as well and should be left alone. So for example:
Regex r = new Regex("a");
will match all occurences of "a" in a string, but:
Regex r = new Regex("^a");
will only match "a" if it occurs at the begining of the string, and:
Regex r = new Regex("a$");
will match it at the end. The trouble is I want to match "a" when it doesn't appear at the begining or the end of a string. There doesn't seem to be a way to say not begining and not end though? Does anybody know if such a thing is possible? I could use:
Regex r = new Regex(".a.");
but that will also match the character before and after the "a" which I don't want to replace.

Cheers

WJ
 
You don't even need to use Regex for that, just iterate through all the characters in the string, when you find a match just check the characters before and after to see if they are
char.IsWhiteSpace(s[i-1]);

Get my drift?
 
That maybe true, and I was in fact doing something similar before, but I want to use regular expressions.
Before I was just using the String.Replace method on a substring of the original string that didn't include the first and last characters, and then tacking the first and last characters back on. Something like this:

newstring = oldstring[0] + oldstring.replace(old,new) + oldstring[oldstring.length-1];

but it's ugly, and I don't like ugly code.
 
Back
Top