如何查找字符串拆分期间使用的分隔符(VB.NET) [英] How to find which delimiter was used during string split (VB.NET)

查看:46
本文介绍了如何查找字符串拆分期间使用的分隔符(VB.NET)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串,我想根据几个字符拆分它,例如 ".""!""?".我如何确定这些字符中的哪一个拆分了我的字符串,以便我可以将相同的字符添加回相关拆分段的末尾?

lets say I have a string that I want to split based on several characters, like ".", "!", and "?". How do I figure out which one of those characters split my string so I can add that same character back on to the end of the split segments in question?

    Dim linePunctuation as Integer = 0
    Dim myString As String = "some text. with punctuation! in it?"

    For i = 1 To Len(myString)
        If Mid$(entireFile, i, 1) = "." Then linePunctuation += 1
    Next

    For i = 1 To Len(myString)
        If Mid$(entireFile, i, 1) = "!" Then linePunctuation += 1
    Next

    For i = 1 To Len(myString)
        If Mid$(entireFile, i, 1) = "?" Then linePunctuation += 1
    Next

    Dim delimiters(3) As Char
    delimiters(0) = "."
    delimiters(1) = "!"
    delimiters(2) = "?"

    currentLineSplit = myString.Split(delimiters)

    Dim sentenceArray(linePunctuation) As String
    Dim count As Integer = 0

    While linePunctuation > 0

        sentenceArray(count) = currentLineSplit(count)'Here I want to add what ever delimiter was used to make the split back onto the string before it is stored in the array.'

        count += 1
        linePunctuation -= 1

    End While

推荐答案

如果您像这样向正则表达式添加捕获组:

If you add a capturing group to your regex like this:

SplitArray = Regex.Split(myString, "([.?!])")

然后返回的数组包含标点符号之间的文本以及每个标点符号字符的单独元素..NET 中的 Split() 函数包括通过捕获返回数组中的组匹配的文本.如果您的正则表达式有多个捕获组,则它们的所有匹配项都包含在数组中.

Then the returned array contains both the text between the punctuation, and separate elements for each punctuation character. The Split() function in .NET includes text matched by capturing groups in the returned array. If your regex has several capturing groups, all their matches are included in the array.

这会将您的样本分成:

some text
.
 with punctuation
!
 in it
?

然后您可以遍历数组以获取句子"和标点符号.

You can then iterate over the array to get your "sentences" and your punctuation.

这篇关于如何查找字符串拆分期间使用的分隔符(VB.NET)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆