2014-12-05 77 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