【问题标题】:Regex help with sample pattern. C#正则表达式帮助示例模式。 C#
【发布时间】:2009-03-23 15:00:22
【问题描述】:

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

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

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

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

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

效果很好。

任何帮助将不胜感激。

【问题讨论】:

  • 为什么将 \\[ 包裹在一个组中?
  • 嗯...我在这里使用旧代码,但是去掉“)”会导致...“解析 \”(\\[[0-9]+\\ ]\" - 不够 ) 的。"异常消息。
  • 您还需要删除 '('。

标签: c# regex


【解决方案1】:
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
}

【讨论】:

  • 考虑到他发布的示例字符串的内容,[%xx] 似乎是十六进制数字的表示法。因此,我不认为匹配任何字符是正确的解决方案。
  • @Samuel - 他的例子可能传达了这一点,但 OP 明确表示“后跟任何长度的字母数字”。顺便说一句,如果它只是十六进制,也许最好让你的解决方案不区分大小写。
  • 不,不是十六进制,很抱歉造成混淆。
  • 干杯,利文。那太完美了。
  • Lieven,是的,不是十六进制,但我意识到我现在拥有的解决方案无论如何都应该不区分大小写,所以感谢您的提醒。
【解决方案2】:

匹配字符串中的“[%anyLengthAlphaNumeric]”模式所需的正则表达式是“[(%\w+)]”

前导“[”用“\”转义,然后您正在使用 (...) 创建一组字符。此分组定义为 %\w+。 \w 是所有单词字符的快捷方式,包括字母和数字,没有空格。 + 匹配前一个符号、字符或组的一个或多个实例。然后尾随的“]”用“\”转义并抓住右括号。

这是一个基本的代码示例:

string input = @"hello world [2] [200] [%8] [%1c] [%d]";
Regex example = new Regex(@"\[(%\w+)\]");
MatchCollection matches = example.Matches(input);

【讨论】:

    【解决方案3】:

    试试这个:

    Regex.Matches(input, "\\[%[0-9a-f]+\\]");
    

    或者作为一个组合的正则表达式:

    Regex.Matches(input, "\\[(\\d+|%[0-9a-f]+)\\]");
    

    【讨论】:

      【解决方案4】:

      @"\[%[0-9a-f]*?\]"怎么样?

      string input = "hello world [2] [200] [%8] [%1c] [%d]";
      MatchCollection matches = Regex.Matches(input, @"\[%[0-9a-f]*?\]");
      matches.Count // = 3
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-10
        相关资源
        最近更新 更多