Find / Replace Word Puzzle
Let's say I have an object that contains a Word property and a Sentence property. The sentence is to use this word and I want to replace the word in this sentence with a link using a public function (like GetLinkedSentence). The trick is, maybe the sentence uses the plural form of the word, and maybe the word "word" itself is actually a phrase, or even hyphenated. There is also no length limit for a word. How do I find and replace this word (in ASP.NET, preferably VB) with a link (www.example.com/? [Word])?
source to share
check this regex (with Expresso, thanks eidylon!):
(?:(?:\b\w+)?{1}(?:{2}|{3})?).+?\b
Where:
{1} = whole word minus the last two letters. for example, if the word "happy" {1} is replaced with "hap"
{2} = second to last letter of the word ("p" if the word is "happy")
{3} = second is the last and last letter of the word ("py" in this example)
this will find "happy" "happy" "unhappy" "unhappy" ... unfortunately for this example it will also find words like "happened", "unhappy", "happening" etc., this will work for me, because I tend to look for more obscure words where the root is less common and the word is a little longer, for example "exacerbates", so it will match "exacerba", "exacerbat" and "exacerbate" "which is less more common than "hap" and "happy". it is also important to note that he will not find a word with extensive radical changes, such as "man" for "people."
so while this is not a PERFECT solution, it works for me :) thanks for pointing me in the right direction, eidilon! now I have a much better understanding of regular expressions!
source to share
Take a look at RegEx.Replace in the System.Text.RegularExpressions namespace.
For example, to replace the word "weather" in the sentence "Weather today is rain". with a link, you can do something like the following:
RegEx.Replace(sSentence, "(weather('s)?)", "<a href='http://www.weather.com'>$1</a>")
The above regex will also replace simple pluralized words (from the end). You can get more complex plural expressions "ies".
source to share