1

I have a string of format:

"one two 33 three"

I need to split it on the numeric value so that I get an array of length 2:

"one two"
"33 three"

or an array of length 3:

"one two"
"33"
"three"

I tried Regex.Split(str,"\D+") but it gave me:

""
"33"
""

and Regex.Split(str,"\d+") gave me:

"one two"
"three"

and Regex.Split(str,"\d") gave me:

"one two"
""
"three"

So none gave me the desired result. Can anyone help?

0

2 Answers 2

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

Split on this regex.

This uses a positive lookahead to check if at the point of split there is an integer separated by word boundary.See demo.

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

EDIT:

If you wanna remove the space too use

(?=\d+\b)

See demo.

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

Sign up to request clarification or add additional context in comments.

3 Comments

Worked like a charm! Could you please explain to me what exactly does it do? Thank you
this will give you a space next to the string two
I have encountered a small problem - some strings contain numeric values as part of a non-numeric string, and this regex splits a string on it. I only need to split on those numeric values that are separated by whitespaces. For example if a string is "ghx-3n 454 test" the regex creates 3 strings, "ghx-", "3n", and "454 test" and I only want two: "ghx-3n" and "454 test". Could you modify it slightly?
1

Use a lookahead in your regex like,

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

(?=\d+) Positive lookahead asserts that the match must be followed by a number. So the above regex would match the space which exists just before to the number. Splitting according to the matched space will give you "one two" "33 three" as result.

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 

Output:

'one two'
'33 three'

IDEONE

To get an array of length 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)

Output:

'one two'
'33'
'three'

IDEONE

1 Comment

that gave me an array of 3 values: {"one two","3" "3 three"} and I wanted {"one two","33" "three"}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.