Ram Cya
Ram Cya

Reputation: 3

Need to create a Regular expression to Split String after first \r\n

I have been stuck in a situation .

Here are few input strings -

 "abacuses\r\n25"

"alphabet\r\n56,\r\n57"

"animals\r\n44,\r\n45,\r\n47"

I need the output to be splited like -

"abacuses\r\n25" to be splitted into A)abacuses B)25


"alphabet\r\n56,\r\n57" to be splitted into A)alphabet B)56,57


"animals\r\n44,\r\n45,\r\n47" to be splitted into A)animals B)44,45,47

So far I have tried this but it doesn't work-

string[] ina = Regex.Split(indexname, @"\r\n\D+");

string[] ina = Regex.Split(indexname, @"\r\n\");

Please Help

Upvotes: 0

Views: 146

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

If you need to split a string at the first \r\n, you may use a String.Split with a count argument:

var line = "animals\r\n44,\r\n45,\r\n47";
var res = line
    .Split(new[] {"\r\n"}, 2, StringSplitOptions.RemoveEmptyEntries);
// Demo output
Console.WriteLine(res[0]);
if (res.GetLength(0) > 1) 
    Console.WriteLine(res[1].Replace("\r\n", "")); // In the second value, linebreaks should be removed

See the C# demo

The 2 in .Split(new[] {"\r\n"}, 2, StringSplitOptions.RemoveEmptyEntries) means that the whole string should be split into 2 parts only and since the string is processed from left to right, the split will occur on the first "\r\n" substring found.

Upvotes: 1

eocron
eocron

Reputation: 7546

No regex needed in your example. You basicaly parse string:

string input = "animals\r\n44,\r\n45,\r\n47";
var split = input.Split(new char[]{'\r','\n',','}, StringSplitOptions.RemoveEmptyEntries);

var name = split[0];                        //animals
var args = string.Join(",", split.Skip(1)); //44,45,37

Many people use it for parsing, but Regex is not a parsing language! It is pattern matcher! It is used to find substrings in string! If you can just Split your string - just do it, really. It is much easier to understand than Regex expression.

Upvotes: 1

Related Questions