gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 23:22:38 30 4
gpt4 key购买 nike

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

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com