Simple regex

I have some form lines

string strA = "Cmd:param1:'C:\\SomePath\SomeFileName.ext':param2"; string strB = "Cmd:'C:\\SomePath\SomeFileName.ext':param2:param3"; 

I want to split this line into ':' so that I can extract N parameters. Some parameters may contain file paths, as shown explicitly, and I do not want to divide by ":", which are in parentheses. I can do this with a regular expression, but I am confused about how to get a regular expression to split only if there is no "." On both sides of the colon.

I tried

 string regex = @"(?<!'):(?!')"; string regex = @"(?<!'(?=')):"; 

which will continue only if there is no left and no right (negative rear / forward appearance), but it is still split into a colon contained in 'C: \ SomePath \ SomeFileName. int.

How to change this regex to do what I need?

Thank you for your time.


Note. I found that the following regex works . However, I would like to know if there is a better way to do this?

 string regex = @"(?<!.*'.*):|:(?!.*'.*)"; 
+4
source share
4 answers

Consider this approach:

 var guid = Guid.NewGuid().ToString(); var r = Regex.Replace(strA, @"'.*'", m => { return m.Value.Replace(":", guid); }) .Split(':') .Select(s => s.Replace(guid, ":")) .ToList(); 
+2
source

Instead of trying to build a lookbehind regex for separation, you can create a regex to match the fields themselves and take a set of matches for this regex. The EG field is either a quoted sequence of non-quotation marks (i.e. it may include : , or it cannot include a delimiter:

 string regex = "'[^']*'|[^':]*"; var result = Regex.Matches(strA, regex); 
+1
source

You want to split into (?<!\b[az]):(?!\\) (use RegexOptions.IgnoreCase ).

+1
source

Not so pretty, but you can replace :\ with safe characters, and then return them back to :\ after splitting.

 string[] param = strA.Replace(@":\", "|||").Split(':').Select(x => x.Replace("|||", @":\")).ToArray(); 
+1
source

Source: https://habr.com/ru/post/1494263/


All Articles