【问题标题】:Regular expression to match every word starting with another word (including special characters)正则表达式匹配以另一个单词开头的每个单词(包括特殊字符)
【发布时间】:2014-10-16 21:37:30
【问题描述】:

我正在使用一个简单的正则表达式来匹配包含以下单词的字符串:

string regExp = @"\b" + searchFor; // searchFor is input value to look for
matchName = Regex.IsMatch(recipient.User.FullName, regExp, RegexOptions.IgnoreCase);

它对单词很有效(当然),但如果 FullName 包含以下内容:

This is Ex$ample

并且用户尝试寻找Ex$a,然后它永远不会匹配。

或者如果用户 searchFor 是:

$ 

对于记录,它始终返回 true。

我尝试查看其他帖子,但找不到类似的内容。

谢谢

**UPDATED**

让我试着解释一下。这个想法是寻找以某些单词开头的名称:

string searchFor = "Gha";

和接收者.用户.全名列表包含:

Jordan Ghassari
James Cunningham
Ghabriel Bercholee 

匹配项必须是:

Jordan Ghassari 
Ghabriel Bercholee 

还需要考虑全名列表可以包含特殊字符。它需要在搜索中包含特殊字符

搜索o^bri 并获得:

O^Brian

搜索#34 并获得:

Depto #345

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    我不确定您的全部问题,但您需要使用Regex escaper 来处理类似这样的问题。 $ 是一个特殊字符。实际搜索美元符号将是\$。您应该查找其他特殊字符并注意它们,尽管 C# 正则表达式转义器会做标记。

    编辑像这样:

    string[] names = 
    {
        "Jordan Ghassari",
        "James Cunningham",
        "Ghabriel Bercholee",
        "O^Brian",
        "Depto #345",
        "This is Ex$ample",
        "$amuel"
    };
    
    string searchFor = Console.ReadLine(); // Input
    searchFor = @"(?:(?<=^|\s)(?=\S|$)|(?<=^|\S)(?=\s|$))" + Regex.Escape(searchFor); // searchFor is input value to look for
    
    Regex regEx = new Regex(searchFor, RegexOptions.IgnoreCase);
    
    List<string> matchedNames = new List<string>();
    foreach(string name in names){
        if (regEx.IsMatch(name))
        {
            matchedNames.Add(name);
        }
    }
    
    foreach (string match in matchedNames) 
    {
        Console.WriteLine(match);
    }
    

    This is a tested and working solution. 您只需转义用户输入的模式部分,然后使用该模式创建一个新的 Regex 对象。 \b 不能用于匹配特殊字符,因此我们使用一些 C# 后视,如 here 所示。然后循环遍历每个字符串并将匹配项存储在某种数据结构中,我选择了一个通用列表。

    【讨论】:

    • 所以你的建议是做 Regex.Escape(searchFor) 和 Regex.Escape(recipient.User.FullName) ?
    • 谢谢@colepanike,你知道为什么如果有像 "$amuel" 和 searchFor = "$am" 这样的名字它永远不会匹配吗?
    • 这是\b 的本质,它只匹配单词字符,特殊字符不属于该列表的一部分。见编辑。
    • 谢谢@colepanike,这就是我要找的。​​span>
    【解决方案2】:

    如果没有 RegEx,这样做可能会更简单:

    string searchString = "This is Ex$ample";
    string searchFor = "Ex$a";
    
    searchString = " " + searchString;
    searchFor = " " + searchFor;
    
    if (searchString.IndexOf(searchFor) >= 0)
    {
        // Match
    } else {
        // No Match
    }
    

    如果您想要不区分大小写的搜索,请改用:

    if (searchString.IndexOf(searchFor, StringComparison.OrdinalIgnoreCase) >= 0)
    {
        // Match
    } else {
        // No Match
    }
    

    【讨论】:

    • IndexOf 不起作用,因为它在 searchString 中的任何位置查找。我需要看看以 searchFor 开头的单词。
    • @ARR01 - 查看我更新的答案,它将仅搜索单词的开头。
    • 谢谢@Icemanind。您的解决方案是正确的,并且是另一种解决方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    相关资源
    最近更新 更多