Skip to main content
 首页 » 编程设计

c#之使用正则表达式获取格式 ABC-XXX-XXX

2024年02月13日30jirigala

我有如下数据

CVE-2011-0573, 
CVE-2011-0606, 
(CVE-2011-0565) 
CVE-2011-0598, 
CVE-2011-0593. 
((CVE-2011-0593.) 

我只需要获取格式“ABC-XXX-XXX”。我使用的正则表达式模式是“[A-Z]{3}-[0-9]{4}-[0-9]{3,10}”。

另外还有一个用C#写的方法

public String RemoveChars(String message) 
{ 
    // The pattern for an expression 
    String charPattern = "[A-Z]{3}-[0-9]{4}-[0-9]{3,10}"; 
    // Create a regex object with the pattern 
    Regex objRegExp = new Regex(charPattern); 
    // Replace unwanted char by empty string - TO BE FIXED(?) 
    message = objRegExp.Replace(message, String.Empty); 
    // Return the message without unwanted chars 
    return message; 
} 

因此,如果我现在运行此代码,对于“CVE-2011-0573,”,它返回“,”而不是“CVE-2011-0573 ”。

能否请您帮我修复该 C# 代码,使其按照结果“CVE-2011-0573”的方式工作?

非常感谢!

请您参考如下方法:

使用这个函数:

public String RemoveChars(String message) 
        { 
            // The pattern for an expression 
            String charPattern = @"[A-Z]{3}-\d{4}-\d{4}"; 
            // Create a regex object with the pattern 
            message = Regex.Match(message, charPattern).Value; 
            // Return the message without unwanted chars 
            return message; 
        } 

此外,如果您需要多个匹配项,请使用 Regex.Matches