How to split prefix character usage with regular expressions?

I would like to break an example line:

~ Peter ~ Lois ~ Chris ~ Meg ~ Stewie

per character ~and get the result

Peter
Lois
Chris
Meg
Stewie

Using the standard line splitting function in javascript or C #, the first result is, of course, an empty string. I would like to avoid ignoring the first result, because the first result may be an empty string.

I was messing around with regex and I'm at a standstill. I am sure that someone has met an elegant solution.

+5
source share
3 answers

For your requirements, I see two options:

(1) , .

(2) .

:

using System;
using System.Linq;
using System.Text.RegularExpressions;

class APP { static void Main() {

string s = "~Peter~Lois~Chris~Meg~Stewie";

// #1 - Trim+Split
Console.WriteLine ("[#1 - Trim+Split]");
string[] result = s.TrimStart('~').Split('~');
foreach (string t in result) { Console.WriteLine("'"+t+"'"); }

// #2 - Regex
Console.WriteLine ("[#2 - Regex]");
Regex RE = new Regex("~([^~]*)");
MatchCollection theMatches = RE.Matches(s);
foreach (Match match in theMatches) { Console.WriteLine("'"+match.Groups[1].Value+"'"); }

// #3 - Regex with LINQ [ modified from @ccook code ]
Console.WriteLine ("[#3 - Regex with LINQ]");
Regex.Matches(s, "~([^~]*)")
    .OfType<Match>()
    .ToList()
    .ForEach(m => Console.WriteLine("'"+m.Groups[1].Value+"'"))
    ;
}}

# 2 , , . ( ). "match.Value" - , , "match.Groups 1.Value" .

(# 3), # 2, LINQ.

, , . . . , , , .

+4

# , :

"~Peter~Lois~Chris~Meg~Stewie".Split("~".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
+1

Here's the LINQ approach ...

Notice with RegexOptions.ExplicitCapture matches are not included. Without it, "~" will also be included.

using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "~Peter~Lois~Chris~Meg~Stewie";
            Regex.Split(s, "(~)", RegexOptions.ExplicitCapture)
                .Where(i=>!String.IsNullOrEmpty(i))
                .ToList().ForEach(i => Console.WriteLine(i));
            Console.ReadLine();
        }
    }
}
+1
source

All Articles