Skip to main content
 首页 » 编程设计

c#之正则表达式帮助示例模式。 C#

2024年02月24日31daizhj

我决定使用正则表达式,现在我有两个问题:)

给定输入字符串“hello world [2] [200] [%8] [%1c] [%d]”,

匹配 "[%8]""[%1c]"+ "[%d]"实例的合适模式是什么? (所以一个百分号,后跟任意长度的字母数字,全部括在方括号中)。

对于“[2]”和[200],我已经使用了

Regex.Matches(input, "(\\[)[0-9]*?\\]"); 

效果很好。

我们将不胜感激。

请您参考如下方法:

MatchCollection matches = null; 
try { 
    Regex regexObj = new Regex(@"\[[%\w]+\]"); 
    matches = regexObj.Matches(input); 
    if (matches.Count > 0) { 
        // Access individual matches using matches.Item[] 
    } else { 
        // Match attempt failed 
    }  
} catch (ArgumentException ex) { 
    // Syntax error in the regular expression 
}