在您的 RegularExpression 中设置您的捕获组,并在组之间粘贴适当的分隔符。
注意:这仅适用于您想要在 3 组数字之间添加逗号的情况。
Imports System
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim str As String = "COND X < 49 300000 200000"
'^ Beginning of the line
'([A-Z]+)\s* capture group 1 that will have any capital letters before the first space,
' but the space is not included in the group
'([A-Z]\s*..?\s*) capture group 2 that will have X (or any single capital letter) plus
' a space, then any character plus a possible character (<=), then a space
'(\d+)\s* capture group 3 & 4 that will have the first group of digits plus a space, but
' the space is not included in the group
'(\d+)$ capture group 5 that will have the last group of digits. $ End of line
Dim pattern As String = "^([A-Z]+)\s*([A-Z]\s*..?\s*)(\d+)\s*(\d+)\s*(\d+)$"
Console.WriteLine(Regex.Replace(str, pattern, "$1($2$3,$4,$5)"))
Console.ReadLine()
End Sub
End Module
结果:
COND(X > 49,300000,200000)
更新
如果您要处理多于三组数字,则使用 Regex.Match 并构建您的字符串允许一次通过。
Imports System
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim str As String = "COND X >= 49 300000 200000 123456 456789"
'([A-Z]+)\s* capture group 1 that will have any capital letters before the first space,
' but the space is not included in the group
'([A-Z]\s*..?\s*) capture group 2 that will have X (or any single capital letter) plus
' a space, then any character plus a possible character (<=), then a space
'(.+)\s* capture group 3 that will have the sets of digits with spaces in between
Dim pattern As String = "([A-Z]+)\s*([A-Z]\s*..?\s*)(.+)"
Dim groups As GroupCollection = Regex.Match(str, pattern).Groups
Console.WriteLine("{0}({1}{2})", groups(1), groups(2), groups(3).Value.Replace(" ", ","))
Console.ReadLine()
End Sub
End Module
结果:
COND(X >= 49,300000,200000,123456,456789)