繁体   English   中英

在VB.NET中使用Regex在数值上拆分字符串

[英]Splitting a string on a numeric value using Regex in 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"

所以没有人给我想要的结果。 有人可以帮忙吗?

(?=\b\d+\b)

在此正则表达式上拆分。

这使用正向前瞻来检查在拆分点是否存在由单词边界分隔的整数。请参阅demo。

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

编辑:

如果您也想删除空间,请使用

(?=\\d+\\b)

参见演示。

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

在正则表达式中使用前瞻,例如

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'

爱迪生

获取长度为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'

爱迪生

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM