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:
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.
Use range() function and slice notation to split a string at every character count in Python.
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);
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);
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With