Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting string on dots but not on dots within round brackets

Tags:

c#

regex

split

I would like to achieve the above but didn't manage it.

I already tried the regex "\.(?![^(]*\))" but it does not work so far.

I want to split the string "replace(<<accountname>>.right(4), Saturn).invert()" like this:

replace(<<accountname>>.right(4), Saturn)
invert()
like image 787
user17582358 Avatar asked Nov 19 '25 19:11

user17582358


1 Answers

You can use a matching approach, i.e. match any one or more occurrences of a string between balanced parentheses or any char other than a .:

var output = Regex.Matches(text, @"(?:\((?>[^()]+|(?<o>)\(|(?<-o>)\))*\)|[^.])+")
    .Cast<Match>()
    .Select(x => x.Value)
    .ToList();

See the .NET regex demo. Details:

  • (?: - start of a "container" non-capturing group:
    • \( - a ( char
    • (?>[^()]+|(?<o>)\(|(?<-o>)\))* - zero or more occurrences (backtracking into the pattern is disabled since the (?>...) is an atomic group, this way the pattern is efficient) of
      • [^()]+| - one or more chars other than a ( and ), or
      • (?<o>)\(| - a ( char, and a value is pushed on to Group "o" capture stack, or
      • (?<-o>)\) - a ) char, and a value is popped off the Group "o" capture stack
    • \) - a ) char
  • | - or
    • [^.] - any char other than a . char
  • )+ - end of the group, repeat one or more times.
like image 177
Wiktor Stribiżew Avatar answered Nov 22 '25 08:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!