如何用多个定界符划分一个字符串,但定界符一直包含在数组中? (VB.NET)

How to divide a string with multiple delimeter, but delimeter is keep include into the array? (VB.NET)

我有一个字符串:

string = "Hello.world, have a nice day"

有没有办法将字符串以点或逗号分割为分隔符,但只将分隔符保留到数组中? (空格是分隔符但不保留)

['Hello','.','world',',','have','a','nice','day']

regex.split(delimeter) 哪个分隔符更好?

这是我的代码

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim arr As String() = Regex.Split(TextBox1.Text, "[.|\,]") For Each i As String In arr Console.WriteLine(i) Next End Sub

抱歉英语不好

如果您想用点或逗号分隔,您可以将字符 class 更新为 [.,],因为字符 class 会匹配任何列出的字符。

字符 class [.|\,] 例如也可以写成 [.,|] 并注意您不必转义逗号。

使用 capture group 来保留分隔符。

你的最终模式看起来像 ([.,])

vb.net demo

例如:

Dim s As String = "Hello.world, have a nice day"
Dim arr As String() = Regex.Split(s, "([.,])")
For Each i As String In arr
    Console.WriteLine(i)
Next

结果:

Hello
.
world
,
 have a nice day