【发布时间】:2011-04-21 17:55:33
【问题描述】:
我想从搜索字段的文本中创建一个字符串列表。 我想将双引号中的任何内容分开。
例如sample' "string's are, more "text" making" 12.34,hello"pineapple sundays
生产
sample'
string's are, more_ //underscore shown to display space
text
making
12.34
hello
pineapple
sundays
编辑:这是我(有点)优雅的解决方案,感谢大家的帮助!
Private Function GetSearchTerms(ByVal searchText As String) As String()
'Clean search string of unwanted characters'
searchText = System.Text.RegularExpressions.Regex.Replace(searchText, "[^a-zA-Z0-9""'.,= ]", "")
'Guarantees the first entry will not be an entry in quotes if the searchkeywords starts with double quotes'
Dim searches As String() = searchText.Replace("""", " "" ").Split("""")
Dim myWords As System.Collections.Generic.List(Of String) = New System.Collections.Generic.List(Of String)
Dim delimiters As String() = New String() {" ", ","}
For index As Integer = 0 To searches.Length - 1
'even is regular text, split up into individual search terms'
If (index Mod 2 = 0) Then
myWords.AddRange(searches(index).Split(delimiters, StringSplitOptions.RemoveEmptyEntries))
Else
'check for unclosed double quote, if so, split it up and add, space we added earlier will get split out'
If (searches.Length Mod 2 = 0 And index = searches.Length - 1) Then
myWords.AddRange(searches(index).Split(delimiters, StringSplitOptions.RemoveEmptyEntries))
Else
'2 double quotes found'
'remove the 2 spaces that we added earlier'
Dim myQuotedString As String = searches(index).Substring(1, searches(index).Length - 2)
If (myQuotedString.Length > 0) Then
myWords.Add(myQuotedString)
End If
End If
End If
Next
Return myWords.ToArray()
End Function
哎,vb 评论太丑了,有人知道怎么清理吗?
【问题讨论】:
-
我的示例字符串中有 5 个引号。我想忽略最后一个没有相应结束引号的。
-
我将在引号之外的所有内容上拆分空格和逗号。
-
如果你这样做要小心,因为如果你基于两个字符分割,有时分割函数实际上会分割字符串两次,一次在第一个字符,第二次在第二个字符,这意味着你会得到中间有一行空白数据。