Hi all
I need a RegEx that allow me to search and replace
words chosen by me (eg. "some" instead of "same").
However, replacement should not happen if the word to replace
represents a resource (a file);
i.e. If some.jpg appears in the text, I don't have to replace anything.
How can I write such a thing?
Thanks in advance.
Luigi
Loading
VulpesPosted Oct 9, 2014, 7:23 AM
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string text1 = "The some loathsome file";
string text2 = "The some file as some.jpg sometimes";
string word = "some";
string replace = "same";
string regExp = @"\b" + word + @"\b(?!\.\w{1,4})";
text1 = Regex.Replace(text1, regExp, replace);
Console.WriteLine(text1);
text2 = Regex.Replace(text2, regExp, replace);
Console.WriteLine(text2);
Console.ReadKey();
}
}
The output is:
The same loathsome file
The same file as some.jpg sometimes
Notice that 'some' is only replaced by 'same' if it's a complete word.
So, 'loathsome' and 'sometimes' are not changed.
Notice also that the regex word boundary meta-character '\b' treats some.jpg as two words: 'some' and '.jpeg'. To avoid replacing 'some' here, we need to use a negative lookahead so it will only be matched if it's not immediately followed by a dot and between 1 and 4 'word' characters.
Luigi ZPosted Oct 9, 2014, 2:18 PM
VulpesPosted Oct 9, 2014, 11:36 AM
So it replaces 'some' with 'same' if it's a full word and not followed by \.\w{1,4} which is a dot and 1 to 4 letters, digits or underscores.
Notice that since dot is a regex meta-character (which matches any character), it needs to be 'escaped' with a back-slash when used literally.
Luigi ZPosted Oct 9, 2014, 8:15 AM
What's mean ?!
L
Luigi ZPosted Oct 9, 2014, 8:09 AM
Munesh SharmaPosted Oct 9, 2014, 6:34 AM
http://dotnet-munesh.blogspot.in/2014/05/searchhighlight-text-in-textbox-or.html