Skip to main content
 首页 » 编程设计

c#之C#正则表达式问题

2024年01月18日38tuyile006

我正在尝试过滤基于正则表达式的文本,例如phone *,这意味着我想要文本“ Phone展位”,“ phone cube”等。

但是当我给展位*时,它也会选择电话亭。它不应该选择仪式吗?这是代码,

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); 
        } 


它显示“电话亭”和“前门”。但是按照我的标准,它不应该显示任何内容,bcoz的任何字符串都不从摊位或门开始。

我的正则表达式有问题吗?

请您参考如下方法:

问题是您没有指定字符串必须以booth或door开头,只是字符串必须包含booth或door后跟长度为零或更大的字符串。

但是,如果将正则表达式更改为^booth.*和^door.*,则一切正常。

应注意,插入符号(^)表示“行/字符串的开头”(取决于您的正则表达式是否处于多行模式-即.是否匹配换行符。)