I am trying to filter out some text based on regex like phone* means i want the text “Phone booth”, “phone cube” etc.
But when I give booth* it selects Phone booth also. It should not select it rite? Here is the code,
string[] names = { "phone booth", "hall way", "parking lot", "front door", "hotel lobby" };
string input = "booth.*, door.*";
string[] patterns = input.Split(new char[] { ',' });
List<string> filtered = new List<string>();
foreach (string pattern in patterns)
{
Regex ex = null;
try
{
ex = new Regex(pattern.Trim());
}
catch { }
if (ex == null) continue;
foreach (string name in names)
{
if (ex.IsMatch(name) && !filtered.Contains(name)) filtered.Add(name);
}
}
foreach (string filteredName in filtered)
{
MessageBox.Show(filteredName);
}
It displays “Phone booth” and “front door”. But as per my criteria, it should not show anything, bcoz no string is starting with booth or door.
Is any problem in my regex?
The problem is that you are not specifying that the string must start with
boothordoor, simply that the string must containboothordoorfollowed by a string of zero-length or greater.If however, you change your Regex to be
^booth.*and^door.*, everything should work.Caret (
^) it should be noted, means “The beginning of the line / string” (depending on whether or not your regular expression is in multiline mode — i.e. if.will match newline characters.)