2014-12-05 83 views
1

使用正則表達式我有格式的字符串數值的字符串:分裂在VB.NET

"one two 33 three" 

我需要將其分裂上的數字值,使得我得到長度爲2的數組:

"one two" 
"33 three" 

或長度3的數組:

"one two" 
"33" 
"three" 

我試圖Regex.Split(str,"\D+")但它給了我:

"" 
"33" 
"" 

Regex.Split(str,"\d+")遞給我:

"one two" 
"three" 

Regex.Split(str,"\d")遞給我:

"one two" 
"" 
"three" 

所以沒有給我想要的結果。誰能幫忙?

回答

3
(?=\b\d+\b) 

拆分這個正則表達式。

這使用積極的前瞻來檢查是否在分裂點有一個整數分隔的字邊界。參見演示。

https://regex101.com/r/wV5tP1/5

編輯:

如果你想刪除的空間也利用

(?=\d+\b)

觀看演示。

https://regex101.com/r/wV5tP1/6

+0

工作就像一個魅力!你能向我解釋它究竟做了什麼?謝謝 – ElenaDBA 2014-12-05 17:06:36

+0

@ElenaDBA請參閱編輯 – vks 2014-12-05 17:08:34

+0

這將給你一個字符串'two'旁邊的空格 – 2014-12-05 17:09:16

1

使用在您的正則像一個前瞻,

Regex.Split(str," (?=\d+)") 

(?=\d+)正預測先行斷言,這場比賽必須遵循的一個數字。所以上面的正則表達式會匹配前面存在的空格。根據匹配的空間分割會給你"one two" "33 three"作爲結果。

Dim input As String = "one two 33 three" 
Dim pattern As String = " (?=\d+)" 
Dim substrings() As String = Regex.Split(input, pattern) 
For Each match As String In substrings 
    Console.WriteLine("'{0}'", match) 
Next 

輸出:

'one two' 
'33 three' 

IDEONE

爲了獲得長度的數組3.

Public Sub Main() 
Dim input As String = "one two 33 three" 
Dim pattern As String = " (?=\d+)|(?<=\b\d+) " 
Dim substrings() As String = Regex.Split(input, pattern) 
For Each match As String In substrings 
Console.WriteLine("'{0}'", match) 

輸出:

'one two' 
'33' 
'three' 

IDEONE

+0

給了我一個3值的數組:{「one two」,「3」「3 three 「}我想{」一個二「,」33「」三「} – ElenaDBA 2014-12-05 17:05:02

+0

不,我編輯了我的答案。你在你的正則表達式中增加了一個空格嗎? – 2014-12-05 17:06:45