vb.net regex.matches没有返回所有匹配项

时间:2013-01-30 01:35:24

标签: php regex vb.net preg-match-all

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:#left#

3:Itema

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

1 个答案:

答案 0 :(得分:0)

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