regex - 如何使用正则表达式将字符串转换为不同的子字符串?

标签 regex vb.net

我有一个包含行的文本文件,类似于这些

000001 , Line 1 of text , customer 1 name
000002 , Line 2 of text , customer 2 name
000003 , Line 3 of text , customer 3 name
  =               =             =
  =               =             =
  =               =             =
000087 , Line 87 of text, customer 87 name
  =               =             =
  =               =             =
001327 , Line 1327 of text, customer 1327 name
  =               =             =
  =               =             =
  =               =             =

我可以编写一个程序,读取上述文件的每一行,将其转换为以下格式:
000001 , 1st Line , 1st Customer name
000002 , 2nd Line , 2nd Customer name
000003 , 3rd Line , 3rd Customer name
  =               =        =
  =               =        =
  =               =        =
000087 , 87th Line, 87th Customer name
  =               =        =
  =               =        =
001327 , 1327th Line, 1327th Customer name
  =               =        =
  =               =        =
  =               =        =

我的问题:是否有使用正则表达式实现相同输出的直接方法?

enter image description here

我尝试了以下方法:
Dim pattern As String = "(\d{6}) , (Line \d+ of text) , (customer \d name)" 
Dim replacement As String = " $1 , $2 Line , $3 Customer name " 
Dim rgx As New Regex(pattern)
Dim result As String = rgx.Replace(my_input_file, replacement)

但结果与预期的输出相差甚远。

请帮忙

最佳答案

您的正则表达式捕获太多。这些组应该只捕获数字:

Dim pattern As String = "(\d{6}) , Line (\d+) of text , customer (\d+) name"

此外,由于您想用序数替换数字,您应该使用 String.Format进行格式化(逐行):
Dim match as Match = rgx.match(my_input_file_line)
Dim outputLine as String = String.Format(" {0} , {1} Line , {2} Customer name", _
    m.Groups(1).Value, GetOrdinal(m.Groups(2).Value), GetOrdinal(m.Groups(3).Value))

哪里GetOrdinal是一种将 number 的字符串更改为序数的方法。

关于regex - 如何使用正则表达式将字符串转换为不同的子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20035948/

相关文章:

regex - 匹配除一个之外的所有单词

vb.net - 编码返回 Double() 以在 VBA 中使用的 .Net 函数

c# - 如何将 Visual Basic 中的代码转换为 C#

javascript - 为逗号分隔的标签列表扩展我的 JavaScript 正则表达式以允许空格

asp.net - IFrame:此内容无法在框架中显示

.net - Console.WriteLine() 与 Debug.WriteLine() 有什么区别?

sql - 使用 ADO .NET 调用 SQL 函数

python - 用正则表达式模式替换

ios - 正则表达式拆分 NSString - iOS

c# - 正则表达式和平衡组