【问题标题】:Ignore pattern errors in a regex search and do not crash the search忽略正则表达式搜索中的模式错误,不要使搜索崩溃
【发布时间】:2021-12-15 08:54:33
【问题描述】:

我正在开发一个正则表达式搜索和替换程序,并希望有一个实时预览,可以立即显示任何更改。

我的问题是,例如,当我打开一个“[”括号时,程序在逻辑上崩溃了,因为 Regex 期望一个括号被关闭。当然,在搜索过程中可能会出现程序崩溃的其他错误。

如果模式错误,我想停止搜索并显示错误消息。

有谁知道在 C# 中使用“IF”查询的解决方案,例如,在执行正则表达式搜索之前检查它是否有效?

或者我怎样才能不崩溃?

using System.Text.RegularExpressions;

public string UseRegex(string input, string search, string replace)
{
    if (???)
    {
        string result = Regex.Replace(input, search, replace);
        return result;
    }
    else
    {
        return "error";
    }
}

【问题讨论】:

    标签: c# regex


    【解决方案1】:

    试试这个:

    public string UseRegex(string input, string search, string replace)
    {
       try
       {
          string result = Regex.Replace(input, search, replace);
          return result;
       }
       catch
       {
          return input;
       }
    }
    

    【讨论】:

    • 它毕竟工作了,当心调试程序,它似乎没有正确使用 try/catch.. TY
    猜你喜欢
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    相关资源
    最近更新 更多