Nick
Nick

Reputation: 1269

c# split string on character when condition is true

I'm looking to use the String.split method in order to split a string on the ':' character. The issue is however that the split is being split on things such as times also. I don't want this to happen. Is there anyway I can specify a predicate which, only when true, the string should be split.

Ideally, I'd only like the strings to be split when the characters either side of the search character are not digits?


Edit:

Example input:

Issued: 08/02/1922 Description: Example Description Time: 03:43

Desired output:

["Issued", " 08/02/1922 Description", " Example Description Time", " 03:43"]

Upvotes: 1

Views: 1339

Answers (3)

King King
King King

Reputation: 63317

You can use Regex for this purpose:

 var output = Regex.Split(input,"(?<!\\d\\s*)\\s*:\\s*|\\s*:\\s*(?!\\s*\\d)");
 //Example:
 string input = "a:b:c:12:00:00";
 //Output
 a
 b
 c
 12:00:00

Upvotes: 3

ya23
ya23

Reputation: 14496

For the example given, simply splitting by ": " (comma followed by space) will do the job. Depending on your data format, it may be good enough for you.

Upvotes: 2

Sushant Srivastava
Sushant Srivastava

Reputation: 761

Use regular expression to find out your string type and then split if it matches your cretirea. Something like below

        Regex r = new Regex(".[0-9]:.[0-9]", RegexOptions.IgnoreCase);
        string s = "00:46";
        Match m = r.Match(s);
        string[] str = !m.Success ? s.Split(':') : null;

Upvotes: 0

Related Questions