Rasmus Eskesen Rasmus Eskesen - 10 months ago 24
Vb.net Question

Splitting String with " ' " but NOT " ?' "

I want to split a String whereever the

character is present unless there is a question mark in front of it(
) - in that case I don't want to split.

What's the best way to go about doing that?

I'm splitting like so (if the delimiter is a Char):

message.Split(New Char() {"'"C})

And if it's a String:

message.Split(New String() {"break"}, StringSplitOptions.None)

Do I then have to test each item in the given array to see if it ends with a
char, and then concatenate the Strings again - that just doesn't seem like an optimal solution..?

Do you have to make a regular expression, and how would you do that in vb.net?


You will need a Regex.Split with a (?<!\?)' regex:

Regex.Split(message, "(?<!\?)'")

See the regex demo

The (?<!\?) negative lookbehind will fail the match if a literal ? appears right to the left of the single apostrophe.

In VB.NET, you can use Linq to remove any empty strings you get with this regex split:

Dim message As String = "'sss?'ss'"
Dim my_result() As String = Regex.Split(message, "(?<!\?)'") _
        .Where(Function(strn As String) String.IsNullOrWhiteSpace(strn) = False) _
Console.WriteLine(String.Join(", ", my_result))
' => sss?'ss

enter image description here