Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a string:

string = "Yellow.car Red.Bag Blue.eyes"

Is there a way to split the string on both periods and whitespaces, but only retain the periods inside the array?


['Yellow','.','Car','Red','.','Bag','Blue','.','Eyes']

A regex for string.split(regexp) would be preferable

What I have tried:

Dim arr As String() = Regex.Split(TextBox1.Text, "(.|,)")
For Each i As String In arr
Console.WriteLine(i)
Next
Posted
Updated 5-Feb-19 23:22pm

Replace the periods with another token that includes a period; then split on the new token.

e.g. if you want to split on "." and keep, then replace "." with "@." or ".@"; then split on "@".
 
Share this answer
 
In a Regex, dot '.' has a specific meaning: "any character". So a regex of "a.b" will match "aab", "abb", "acb", ... any character between an a and a b.
So your regex: "(.|,)" is "either any character or a comma" - which amounts to "any character!

You can escape it so that it becomes a literal: "(\.|,)" which is "either dot or comma" but for single character values there is a better syntax: "[\.,]" which does the same thing.
 
Share this answer
 
Quote:
A regex for string.split(regexp) would be preferable

Advice: study RegEx, there is more than 1 way to use it.
Split is used to cut a string on separator and separator is lost.
Match on the other side will make a list of every match in string. you just have to build a RegEx that will match "a word or a point".
A RegEx like \w+|\. should all what you want.

Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx: Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
This site also show the Regex in a nice graph but can't test what match the RegEx: Regexper[^]
 
Share this answer
 
v2
Try this:
VB
Dim s As String = "Yellow.car Red.Bag Blue.eyes"
s = s.Replace(".", " . ")
Dim result = String.Join(",", s.Split(New String(){" "}, StringSplitOptions.RemoveEmptyEntries).Select(Function(w) String.Concat("'", w, "'")))


Result:
'Yellow','.','car','Red','.','Bag','Blue','.','eyes'


As you see, the logic is very simple:
1) replace dot with dot with spaces around it,
2) split string on spaces and add ['] around each part,
3) join parts with commas.

That's all!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900