Posted: 5/20/2010
Hi,
I need to make a regex where I need to match whether a string contains any of the particular set of words. For example:
I have a test string I need to check whether this string contains any of these words "c#,sql,vb,java"
Please help me.
Take a look at the following example which I've prepared for you:
Sentence <asp:TextBox ID="TextBox1" runat="server" Width="467px"></asp:TextBox> <br /> Words <asp:TextBox ID="TextBox2" runat="server" Width="467px"></asp:TextBox> <br /> <br /> <asp:Button ID="btnFindWords" runat="server" onclick="btnFindWords_Click" Text="REGEX FIND" /> <br /> <asp:Label ID="lblFound" runat="server"></asp:Label>
code-behind
protected void btnFindWords_Click(object sender, EventArgs e) { string sentence = TextBox1.Text; string words = TextBox2.Text; string constructRegex = String.Empty; constructRegex += "|"; foreach (string word in words.Split(',')) { constructRegex += word + "|"; } Regex expr = new Regex("\b"+constructRegex+"\b", RegexOptions.IgnoreCase); foreach (Match m in expr.Matches(sentence)) { lblFound.Text += m.Value + " "; } }
Im creating regEx dynamically. Basically the regEx to find words in a sentence is: \b|word1|word2|word3|\b
Hope this helps,Hajan
Posted: 5/21/2010
This will serve you : (c#|sql|vb|java)
Try this sample:
#region Using Directives using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; using System.Collections; using System.Text.RegularExpressions; #endregion public class Example { public static void Main() { const string inputString = "I have c#"; var regex = new Regex(@"(c#|sql|vb|java)", RegexOptions.Singleline | RegexOptions.IgnoreCase); Console.WriteLine(regex.IsMatch(inputString) ? "Matched" : "Not matched"); const string inputString2 = "I have php"; Console.WriteLine(regex.IsMatch(inputString2) ? "Matched" : "Not matched"); const string inputString3 = "I have sql vb"; Console.WriteLine(regex.IsMatch(inputString3) ? "Matched" : "Not matched"); Console.ReadLine(); } }
Output:
Matched
Not matched