2010-03-19 73 views
2

我正在使用下面的代碼來獲取一個字符串並將其分成一個數組。它將採取:迪斯尼樂園並將其分爲兩個獨立的元素。如果字符串包含「迪斯尼樂園」,那麼它就是數組中的一個元素。很好用,但它每次都會爲數組添加一些空元素。所以我只是遍歷元素,如果它們是空的,就將它們移除。是否對下面的代碼進行了調整,以防止這些空元素髮生?.NET正則表達式來分割多個單詞或短語

Private m_Reg As Regex 
m_Reg = New Regex("([^""^\s]+)\s*|""([^""]+)""\s*") 
Dim rezsplit = m_Reg.Split(criteria) 

回答

2

Alan的回答是正確的。使用他的模式,我們可以使用LINQ來過濾Split結果,或者我們可以按照他的建議使用Matches

Dim input As String = "Islands of Adventure ""Disney Land"" Universal Studios" 
Dim pattern As String = "(?<Value>[^""\s]+)|""(?<Value>[^""]+)""" 
Dim result = Regex.Split(input, pattern).Where(Function(s) s.Trim <> "") 

Console.WriteLine("Split Result:") 
For Each s In result 
    Console.WriteLine(s) 
Next 

Console.WriteLine("Matches:") 
For Each m As Match In Regex.Matches(input, pattern) 
    Console.WriteLine(m.Groups("Value").Value) 
Next 

''# to get string arrays use either of these instead 
Dim splitArray As String() = Regex.Split(input, pattern) _ 
           .Where(Function(s) s.Trim <> "") _ 
           .ToArray() 
Dim matchArray As String() = Regex.Matches(input, pattern).Cast(Of Match) _ 
            .Select(Function(m) m.Groups("Value").Value) _ 
            .ToArray() 
+0

非常感謝你。 – 2010-03-20 21:23:23

+0

@Cj很高興幫助:) – 2010-03-20 22:08:17

2

使用Matches而不是Split,你將不必擔心。你也可以簡化正則表達式:

m_Reg = New Regex("""([^""]+)""|[^""\s]+") 

編輯:我忘了處理刮報價的問題。這將使它更容易:

m_Reg = New Regex("""(?<Value>[^""]+)""|(?<Value>[^""\s]+)") 

現在,無論哪種替代匹配,可在名爲「值」的組中找到所需的文本。

+0

我正在嘗試它,但它返回一個匹配集合。我需要一個String()。我試過ctype,然後嘗試copyto方法。我不知道如何在沒有迭代集合的情況下將它變成一個字符串。我已經在迭代集合以擺脫空串,所以我希望避免這種情況。 – 2010-03-19 21:41:21

+0

我在.NET中並不流利,但如果沒有將MatchCollection作爲String數組裝飾的方法,我會感到非常驚訝。 Linq,也許? – 2010-03-19 22:05:05

+0

+1。我發佈了.NET方法。 – 2010-03-19 23:54:52