【问题标题】:Extract variables from pattern matching从模式匹配中提取变量
【发布时间】:2015-03-04 00:37:54
【问题描述】:

我不是匹配模式专家,我已经为此工作了几个小时,但没有机会:/

我有一个这样的输入字符串:

Dim text As String = "32 Barcelona {GM C} 2 {*** Some ""cool"" text here}"

我只想提取 3 件事:

  1. 巴塞罗那
  2. GM C
  3. *** 这里有一些“很酷”的文字

我正在尝试的模式是这样的:

Dim pattern As String = "^32\s(?<city>[^]].*\s)\{(?<titles>.*\})*"

Dim m As Match = Regex.Match(text, pattern)

If (m.Success) Then

    Dim group1 As Group = m.Groups.Item("city")
    Dim group2 As Group = m.Groups.Item("titles")

    If group1.Success Then
        MsgBox("City:" + group1.Value + ":", MsgBoxStyle.Information)   
    End If

    If group2.Success Then
        MsgBox(group2.Value, MsgBoxStyle.Information)  
    End If
    Else
        MsgBox("fail")
    End If

但无论如何它都不起作用:( 提取这 3 个变量的模式应该是什么?

【问题讨论】:

  • “酷”文本是否有任何限制?如果不是,RegEx 可能不是最佳选择,因为您的输入不符合“常规”输入的正式定义。
  • 再想一想,您可能仍然可以这样做,因为您可以将所有内容都保存到字符串的末尾。

标签: regex vb.net match extraction


【解决方案1】:

^\d*(?&lt;City&gt;[A-Z a-z0-9]*)\s*\{(?&lt;Titles&gt;[A-Z a-z0-9]*)\}.*?\{(?&lt;Cool&gt;.*?)\}$

似乎与您的示例输入相匹配。

Expresso 是设计正则表达式的好工具。

【讨论】:

  • 工作得几乎很棒。想我的方法如何使用它。我猜模式 "^\d*\s(?.*?)\s\{(?.*)\}.*?\{(?.*?)\} $" 更适合我的情况。
猜你喜欢
  • 2010-10-27
  • 1970-01-01
  • 2013-08-15
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
相关资源
最近更新 更多