【问题标题】:Regex excluding all numbers正则表达式不包括所有数字
【发布时间】:2017-04-24 08:03:29
【问题描述】:

您好,我正在尝试通过 VB.NET 中的正则表达式搜索文件中的所有匹配表达式 我有这个功能:

Dim written As MatchCollection = Regex.Matches(ToTreat, "\bGlobalIndexImage = \'(?![0-9])([A-Za-z])\w+\'")
For Each writ As Match In written
    For Each w As Capture In writ.Captures
        MsgBox(w.Value.ToString)
    Next
Next

我现在有这个正则表达式:

\bGlobalIndexImage = \'(?![0-9])([A-Za-z])\w+\'

我正在尝试匹配此表单下的所有匹配项:

GlobalIndexImage = 'images'
GlobalIndexImage = 'Search'

但我也得到这样的值,我不想匹配:

GlobalIndexImage = 'Z0003_S16G2'

所以我想在我的正则表达式中简单地排除包含数字的匹配项。

【问题讨论】:

    标签: regex vb.net


    【解决方案1】:

    \w 速记字符类匹配字母数字_。如果您只需要字母,请使用[a-zA-Z]

    "\bGlobalIndexImage = '([A-Za-z]+)'"
    

    请参阅regex demo

    详情

    • \b - 前导词边界
    • GlobalIndexImage = ' - 一串文字字符
    • ([A-Za-z]+) - 第 1 组捕获一个或多个(由于 + 量词)ASCII 字母
    • ' - 单引号。

    如果您需要匹配任何 Unicode 字母,请将 [a-zA-Z] 替换为 \p{L}

    VB.NET:

    Dim text = "GlobalIndexImage = 'images' GlobalIndexImage = 'Search'"
    Dim pattern As String = "\bGlobalIndexImage = '([A-Za-z]+)'"
    Dim matches As List(Of String) = Regex.Matches(text, pattern) _
                                        .Cast(Of Match)() _
                                        .Select(Function(m) m.Groups(1).Value) _
                                        .ToList()
    Console.WriteLine(String.Join(vbLf, matches))
    

    输出:

    【讨论】:

    • 感谢完美。在同一场合,您知道是否有一种快速的方法可以通过 vb.net 获得您图片中显示的 1 美元?
    • 您更喜欢 Linq 方法吗?
    • 我也不介意我可以简单地拆分 ' 上的字符串但是我可能已经有一种方法可以做到这一点。
    • 没有特定的方法可以仅提取特定的组值。使用Regex.Matches,遍历匹配并收集.Group(1).Value
    【解决方案2】:

    要捕获不是数字的所有内容,请使用\D

    所以你的正则表达式会是这样的

    \bGlobalIndexImage = \'\d+\'
    

    但这也将包括带有空格的单词。要仅获取字母,请使用 [a-zA-Z]

    \bGlobalIndexImage = \'[a-zA-Z]+\'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-02
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多