Regular Expression Help

Wjousts

Member
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 doesnt appear at the begining or the end of a string. There doesnt 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 dont want to replace.

Cheers

WJ
 
You dont 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 didnt 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 its ugly, and I dont like ugly code.
 

Similar threads

R
Replies
0
Views
124
Richard.Haggard
R
E
Replies
0
Views
90
etl2016
E
N
Replies
0
Views
89
Narayana Reddy GundReddy
N
I
Replies
0
Views
153
Innovators World Wide
I
Back
Top