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

Ahm*_*mad 4 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
  =               =             =
  =               =             =
  =               =             =
Run Code Online (Sandbox Code Playgroud)

我可以编写一个程序来读取上面文件的每一行,将其转换为以下格式:

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
  =               =        =
  =               =        =
  =               =        =
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

我尝试了以下方法:

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)
Run Code Online (Sandbox Code Playgroud)

但结果远不是理想的输出.

请帮忙

Szy*_*mon 5

你的正则表达式捕获太多了.这些组应仅捕获数字:

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

另外,由于您想用序数替换数字,您应该使用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))
Run Code Online (Sandbox Code Playgroud)

where GetOrdinal是一个将数字字符串更改为序数的方法.