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

标签 c# regex

我有一个 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> 

关于c# - 为什么 C# 不遵循我的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6957559/

相关文章:

regex - htaccess 将带或不带尾部斜杠的 url 重定向到新 url

javascript - 为什么连续前瞻并不总是有效

javascript - 如何在表单提交时阻止坏词

c# - 部分类中的自定义属性(无效的列名称)

c# - 泛型无法推断第二个参数?

c# - 这个导致我在 Excel 电子表格中看到绿色三角形的公式有什么问题?

c# - 仅当使用 "produce single file"选项发布时,Newtonsoft.Json 文件未找到异常

python - 如何查找以ing结尾的单词

regex - T-SQL LIKE 正则表达式

c# - .NET 中的 xslt:param 数组