c# - 删除可选的最后一个括号

标签 c# regex

我正在尝试解析文件名并删除括号中的潜在数字(当有多个文件具有相同的基本名称时),但只删除最后一个

以下是一些预期结果:

  1. 测试 ==> 测试
  2. 测试(1) ==> 测试
  3. 测试(1)(2) ==> 测试(1)
  4. 测试 (123) (232) ==> 测试 (123)
  5. 测试 (1) foo ==> 测试 (1) foo

我尝试使用此正则表达式:(.*)( ?\(\d+\))+,但测试 1 失败。

我也尝试过:(.*)( ?\(\d+\))? 但只有第一次测试成功。

我怀疑正则表达式中的量词有问题,但我没有找到确切的问题。

如何修复我的正则表达式?

最佳答案

我的猜测是您可能希望设计类似于以下的表达式:

^(.*?)\s*(\(\s*\d+\)\s*)?$

测试

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"^(.*?)\s*(\(\s*\d+\)\s*)?$";
        string input = @"Test
Test (1)
Test (1) (2)
Test (1) (2) (3)
Test (1) (2)    (3) (4) 
";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

表达式在 regex101.com 的右上面板中进行了解释, 如果你想探索/简化/修改它,在this link ,如果愿意,您可以观察它如何与一些样本输入相匹配。

正则表达式电路

jex.im可视化正则表达式:

enter image description here

关于c# - 删除可选的最后一个括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57166285/

相关文章:

Javascript 正则表达式仅允许 2 位数字和 3 位数字以逗号分隔

c# - 模拟和单例

c# - 在使用 .NET 驱动程序插入 MongoDB 之前验证文档

java - 制作一个单弦线计算器

regex - 从 shell 脚本中的字符串中过滤非字母字符

Javascript - 使用全局修饰符删除最后一个不起作用

c# - Visual Studio 2017 中的 Windows Forms Application menuStrip 比 2019 更方便?

c# - REST 服务中的 POST 请求为空

c# - 使用 SandcaSTLe : Refering to enum value using <see> 记录

regex - HTML5 模式验证