0
Dim pattern As String = "^[ \t]*(\d+)[ \t]*(#[^#]*#)?[ \t]*(\w+)[ \t]?(.*)$"
Dim sentence As String = "9 #Left# Itema Desc"

For Each match As Match In Regex.Matches(sentence, pattern)
  Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index)
Next

只返回:

在位置 0 找到“9 #Left# Itema Desc”

使用 Expresso 测试上面的 vb 模式返回:

1:9

2:#左#

3:意达

4:描述

此外,这个 PHP 正则表达式还返回四项:

preg_match_all('/^[ \t]*(\d+)[ \t]*(#[^#]*#)?[ \t]*(\w+)[ \t]?(.*)$/m', $in, $matches, PREG_SET_ORDER);

我究竟做错了什么??

提前致谢!

多亏了 Ark-kun,我的问题确实是组 - 这是有效的代码:

Dim pattern As String = "^[ \t]*(\d+)[ \t]*(#[^#]*#)?[ \t]*(\w+)[ \t]?(.*)$"
Dim sentence As String = "9 #Left# Itema Desc"

Dim match As Match = Regex.Match(sentence, pattern)
If match.Success Then
  Console.WriteLine("Matched text: {0}", match.Value)
    For ctr As Integer = 1 To match.Groups.Count - 1
      Console.WriteLine("   Group {0}:  {1}", ctr, match.Groups(ctr).Value)
    Next
 End If
4

1 回答 1

0

结果在逻辑上是正确的。您已经编写了“整行”正则表达式,并且该Regex.Matches方法找到了一个匹配项 - 整行。您可能想要的是match.Captures属性:http: //msdn.microsoft.com/en-us/library/system.text.regularexpressions.group.captures.aspx

于 2013-01-30T02:35:34.620 回答