Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split by '/' till '[' appears

Tags:

c#

regex

I want to split the following kind of string:

Parent/Child/Value [4za] AX/BY

and get create a String[] out of it via:

String[] ArrayVar = Regex.Split(stringVar, "?");

which split the string by every / before first appearance of [.

So as result I would get

Array[0] => "Parent"
Array[1] => "Child"
Array[2] => "Value [4za] AX/BY"

strings could also have other formats like

Parent/Value [4za] AX/BY

Value [4za] AX/BY

How can I do this?

like image 231
user3137112 Avatar asked Apr 25 '17 09:04

user3137112


Video Answer


2 Answers

You could use normal string operations to do this. Just split the string on the first [ then split that accordingly. Then just add the end part of the string onto the last element:

string inputstring = "Parent/Child/Value [4za] AX/BY";

int index = inputstring.IndexOf('[');

string[] parts = inputstring.Substring(0, index).Split('/');
parts[parts.Length - 1] += inputstring.Substring(index);
like image 195
TheLethalCoder Avatar answered Sep 22 '22 06:09

TheLethalCoder


Use negative lookbehind ((?<!...)). The following regex means "/ not preceded by opening bracket":

(?<!\[.*)/

Demo

C# demo: https://dotnetfiddle.net/85S3cK

like image 30
Dmitry Egorov Avatar answered Sep 26 '22 06:09

Dmitry Egorov