Reputation: 1049
I have some doubts about what I'm doing. I try to remove pices of text like the letter "n" where it is between a "(" and a " " or viceversa, and many other cases. I use regex to find the pattern, but how can I delete only the letter?
I've used this: "[( ]" + mystring + @"[)= \-\*]"
like this:
foreach(Match mm in Regex.Matches(SourceCode, @"[( ]" + mystring + @"[)= \-\*]"))
{
int lng= mm.Length;
SourceCode = SourceCode.Remove(mm.Index + 1, lng- 2);
}
The problem is that it calculates the index for the original text, and if there will be removed a "n" the index for the next match will be decalated with one and will delete from a wrong place. Really strange.
Does anybody know what it is doing that?
Or maybe do you have a better ideea?
Edit:
I can't use replace. Let's say I want to delete "n" where n is like "(n " so if I use replace it will delete all those three characters wich I don want. If I use replace only for n, it will delete wrong letter like the "n" from "and" . . .
Upvotes: 0
Views: 98
Reputation: 336128
Your question is a bit hard to read, but I think what you need is a replace operation, together with lookaround assertions:
SourceCode = Regex.Replace(SourceCode, "(?<=[( ])" + mystring + "(?=[)= *-])", "");
This will replace the regex mystring
with nothing, but only if it is preceded by a (
or space, and followed by )
, =
, *
, -
or space.
If you want mystring
to be interpreted as a string, not as a regex, you should use Regex.Escape(mystring)
instead of mystring
.
Upvotes: 4