【问题标题】:Value of Type Match Cannot Be Converted To String类型匹配的值不能转换为字符串
【发布时间】:2019-02-13 20:10:49
【问题描述】:

我目前正在尝试遍历一个包含文本文件的文件夹并阅读它们。在我阅读它们之后,我想使用正则表达式提取文件名的一部分,但是我收到了错误Value of Type Match Cannot Be Converted To String

我尝试过使用Cstr,但这似乎不能解决我的问题。

我正在使用的代码:

 Dim fileentries As String() = Directory.GetFiles("D:\User\BackUp\Project\bin\Debug\Orders")
 For Each entry In fileentries
        Dim match As New List(Of String)
        Dim regexmatch As Match = Regex.Match(entry, "Order_\d\d-\d\d-[\d]{4}_[\d]{6}")
        match.Add(CStr(regexmatch))

    Next

这里的正则表达式部分正在工作,它似乎提取了我想要的文件名的正确部分,但特别是 match.Add(Cstr(regexmatch)) 行,我收到了我所描述的错误。

感谢您的帮助,谢谢。

【问题讨论】:

  • 因为Match不是String...Regex.Match返回一个包含匹配信息的对象(你需要Value属性),请read more here
  • 查看这些答案中的任何一个,可能与VB.Net Regex...extracting a value重复
  • 我应该记得先看那里,应该只是按 F1。我会记住这一点的。

标签: .net regex vb.net


【解决方案1】:

您需要访问Match对象的.Value属性,但建议检查是否完全匹配:

Dim regexmatch As Match = Regex.Match(entry, "Order_\d\d-\d\d-\d{4}_\d{6}")
If regexmatch.Success Then
    match.Add(regexmatch.Value)
End If

VB.NET demo

Imports System.Collections.Generic
Imports System.Text.RegularExpressions
' ... 
Dim match As New List(Of String)()
Dim entry As String = "XXXX_Order_12-12-1234_123456_irrelevant.txt"
Dim regexmatch As Match = Regex.Match(entry, "Order_\d\d-\d\d-\d{4}_\d{6}")
If regexmatch.Success Then
    match.Add(regexmatch.Value)
End If
Console.WriteLine(match(0)) ' => Order_12-12-1234_123456

注意[\d]{4} 等于\d{4},不需要将单个原子放入字符类中。

【讨论】:

  • 谢谢,我意识到这很简单,就像添加 .Value 但是现在它已经清理干净并且循环正常工作了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 2013-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多