Skip to main content
 首页 » 编程设计

c#之为什么 C# 不遵循我的正则表达式

2024年01月18日37webabcd

我有一个 C# 应用程序,它读取一个单词文件并查找包含在 < brackets > 中的单词

它当前使用以下代码和显示的正则表达式。

 private readonly Regex _regex = new Regex("([<])([^>]*)([>])", RegexOptions.Compiled); 

我已经使用了几个在线测试工具/ friend 来验证正则表达式是否有效,我的应用程序证明了这一点(对于那些在家玩的人,http://wordfiller.codeplex.com)!

但我的问题是正则表达式也会收集额外的垃圾。

E.G

I'm walking on <sunshine>. 

会回来

sunshine>. 

它应该只是返回

<sunshine> 

有人知道为什么我的应用程序拒绝遵守规则吗?

请您参考如下方法:

我认为问题根本不是您的正则表达式。它可以有所改进——你不需要 ([])每个括号周围 - 但这不应该影响结果。 我强烈怀疑问题出在您的 C# 实现中,而不是您的正则表达式。

你的正则表达式应该拆分 <sunshine>分为三个独立的组:< , sunshine , 和 > .使用下面的代码对其进行测试后,这正是它的作用。我怀疑,在 C# 代码的某处,您在没有意识到的情况下将第 3 组附加到第 2 组。一些快速的 C# 实验支持这一点:

private readonly Regex _regex = new Regex("([<])([^>]*)([>])", RegexOptions.Compiled); 
private string sunshine() 
{ 
    string input = "I'm walking on <sunshine>."; 
    var match = _regex.Match(input); 
    var regex2 = new Regex("<[^>]*>", RegexOptions.Compiled); //A slightly simpler version 
 
    string result = ""; 
 
    for (int i = 0; i < match.Groups.Count; i++) 
    { 
        result += string.Format("Group {0}: {1}\n", i, match.Groups[i].Value); 
    } 
 
    result += "\nWhat you're getting: " + match.Groups[2].Value + match.Groups[3].Value; 
    result += "\nWhat you want: " + match.Groups[0].Value + " or " + match.Value;         
    result += "\nBut you don't need all those brackets and groups: " + regex2.Match(input).Value; 
 
    return result; 
} 

结果:

Group 0: <sunshine> 
Group 1: < 
Group 2: sunshine 
Group 3: > 
 
What you're getting: sunshine> 
What you want: <sunshine> or <sunshine>  
But you don't need all those brackets and groups: <sunshine>