Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string on the 3rd occurence of a char C#

Tags:

c#

I was wondering is there a way to split a string on the 3rd occurence of a char? When splitting previously i was using:

line.Substring(line.LastIndexOf(']') +1);

I hadn't realised some of my strings had extra square brackets than others so ideally i need to split on the 3rd occurence of ']' as this is the same position on every string.

Input: [Wed Dec 17 14:40:28 2014] [error] [client 143.117.101.166] File does not exist:

Output:

[Wed Dec 17 14:40:28 2014] [error] [client 143.117.101.166]

File does not exist:

like image 500
Michael Avatar asked Apr 14 '17 12:04

Michael


People also ask

How do you split a string on the first occurrence of certain characters?

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

How do I split a string by character count?

Use range() function and slice notation to split a string at every character count in Python.

How split a string after a specific character in C#?

Split(char[], StringSplitOptions) Method This method is used to splits a string into substrings based on the characters in an array. You can specify whether the substrings include empty array elements. Syntax: public String[] Split(char[] separator, StringSplitOptions option);


3 Answers

you need to split the string first then take the index of the 3rd ]

line.Substring(line.IndexOf(line.Split(']')[3]));

or more easy as you said the 3rd index of ] is the same, put it fixed

line.Substring(59);
like image 118
Bassel Eid Avatar answered Nov 14 '22 21:11

Bassel Eid


This input can be matched with a regular expression:

\[[^\]]*\]\s*\[[^\]]*\]\s*\[[^\]]*\]

This looks scary because of escape sequences, but the structure is very straightforward: it matches three occurrences of [ + zero or more non-] + ], separated by zero or more spaces.

var s = "[Wed Dec 17 14:40:28 2014] [error] [client 143.117.101.166] File does not exist:";
var r = new Regex(@"(\[[^\]]*\]\s*\[[^\]]*\]\s*\[[^\]]*\])(.*)$");
var m = r.Match(s);
if (m.Success) {
    Console.WriteLine("Prefix: {0}", m.Groups[1]);
    Console.WriteLine("Error: {0}", m.Groups[2]);
}

Demo.

like image 32
Sergey Kalinichenko Avatar answered Nov 14 '22 22:11

Sergey Kalinichenko


Use Regex to solve the problem,this will capture content with []

string input = " [Wed Dec 17 14:40:28 2014] [error] [client 143.117.101.166] File does not exist";
var regex = new Regex("\\[(.*?)\\]");
var matches = regex.Matches(input);
foreach (var match in matches) // e.g. you can loop through your matches like this
{
   //yourmatch
}
like image 36
Arash Avatar answered Nov 14 '22 21:11

Arash