首页 文章

如何匹配整个字符串而不仅仅是部分?

提问于
浏览
0

我有一个正则表的列表,我迭代,找到一个字符串的匹配模式 .

我想获得与“00000.00”完全匹配的正则表达式的索引,即1.然而,正则表达式0也返回true,但是如果有长度为5或6的数字或字符串,则只返回true .

含义12345和123456应该有效,但12345.0或123456.0不应该有效 .

List<Regex> regexPatterns = new List<Regex>{
    new Regex(@"\b\d{5,6}\b"),              // 0
    new Regex(@"\b\d{5,6}[.](00)\b")        // 1
}

string text = "00000.00";

for( int i = 0; i < regexPatterns.Count; i++ ) {
    if( regexPatterns.IsMatch(text) ) return i;
}

当我希望它返回1时,这为00000.00保持返回0 .

**索引有意义,所以重新排序是不可能的 .

3 回答

  • 0

    尝试 ^$ 作为字符串的开头和结尾:

    List<Regex> regexPatterns = new List<Regex>{
        new Regex(@"^\d{5,6}$"),              // 0
        new Regex(@"^\d{5,6}[.](00)$"),       // 1
    }
    

    Regular Expression Language - Quick Reference

    ^匹配必须从字符串或行的开头开始 . $匹配必须发生在字符串的末尾,或者在行或字符串末尾的\ n之前 .

  • 2

    由于这个时期将充当一个边界,你最好的选择是从最复杂的模式扫描到最简单的模式 . 您可以执行for循环递减来完成此操作,但另一种考虑方法是使用模式的字典,其中值组件是返回值 .

    var patterns = new Dictionary<string, int>
        {
            { @"\b\d{5,6}\b", 0 },
            { @"\b\d{5,6}[.](00)\b", 1 },
        };
    
    string text = "00000.00";
    
    foreach (var pattern in patterns.Keys)
    {
        if (pattern.IsMatch(text))
            return patterns[pattern];
    }
    
  • 0

    检查第一个中没有句号:

    List<Regex> regexPatterns = new List<Regex>{
        new Regex(@"\d{5,6}[^.]"),              // 0
        new Regex(@"\d{5,6}[.](00)")        // 1
    }
    
    string text = "00000.00";
    
    for( int i = 0; i < regexPatterns.Count; i++ ) {
        if( regexPatterns.IsMatch(text) ) return i;
    }
    

相关问题