I need some help on Regex. I need to find a word that is surrounded by whatever element, for example – *. But I need to match it only if it has spaces or nothing on the ether sides. For example if it is at start of the text I can’t really have space there, same for end.
Here is what I came up to
string myString = "You will find *me*, and *me* also!";
string findString = @"(\*(.*?)\*)";
string foundText;
MatchCollection matchCollection = Regex.Matches(myString, findString);
foreach (Match match in matchCollection)
{
foundText = match.Value.Replace("*", "");
myString = myString.Replace(match.Value, "->" + foundText + "<-");
match.NextMatch();
}
Console.WriteLine(myString);
You will find ->me<-, and ->me<- also!
Works correct, the problem is when I add * in the middle of text, I don’t want it to match then.
Example: You will find *m*e*, and *me* also!
Output: You will find ->m<-e->, and <-me* also!
How can I fix that?
Try the following pattern:
(?<=\s|^)Xwill match anyXonly if preceded by a space-char (\s), or the start-of-input, andX(?=\s|$)matches anyXif followed by a space-char (\s), or the end-of-input.Note that it will not match
*me*infoo *me*, barsince the second*has a,after it! If you want to match that too, you need to include the comma like this:You’ll need to expand the set
[\s,]as you see fit, of course. You might want to add!,?and.at the very least:[\s,!?.](and no,.and?do not need to be escaped inside a character-set!).EDIT
A small demo:
which would print: