Skip to content

Instantly share code, notes, and snippets.

@JerryNixon
Last active January 5, 2021 01:00
Show Gist options
  • Select an option

  • Save JerryNixon/1571cf101517fae62786538b778a10b2 to your computer and use it in GitHub Desktop.

Select an option

Save JerryNixon/1571cf101517fae62786538b778a10b2 to your computer and use it in GitHub Desktop.
Balance Parentheses in a string
// netcoreapp3.1
using System;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
namespace Jerry
{
class Program
{
private static readonly Regex _regex = new Regex(_pattern);
private static readonly Stopwatch _stopwatch = new Stopwatch();
private static readonly Random _random = new Random((int)DateTime.Now.Ticks);
private const string _pattern = @"\((?>\((?<parens>)|[^()]+|\)(?<-parens>))*(?(parens)(?!))\)";
static void Main(string[] args)
{
Do(10);
Do(10);
Do(10);
Do(20);
Do(30);
void Do(int size)
{
// create random (()()() string and append invalid text at the end.
var input = string.Join(string.Empty, Enumerable.Range(1, size).Select(x => (char)_random.Next(40, 42))) + "JerryNixon";
// start measuring
_stopwatch.Restart();
// look for pattern match in the string, return all found
var output = string.Join(string.Empty, _regex.Matches(input).Select(x => x.Value));
// stop measuring
_stopwatch.Stop();
// output
Console.WriteLine($"\r\nSize: {size}\r\nInput: {input}\r\nOutput: {output}\r\nTime: {_stopwatch.Elapsed}");
}
}
}
}
@JerryNixon

Copy link
Copy Markdown
Author

Some references:

A balancing group definition deletes the definition of a previously defined group and stores, in the current group, the interval between the previously defined group and the current group. This grouping construct has the following format:

(?<name1-name2>subexpression) or (?'name1-name2' subexpression)

Backreferences provide a convenient way to identify a repeated character or substring within a string. For example, if the input string contains multiple occurrences of an arbitrary substring, you can match the first occurrence with a capturing group, and then use a backreference to match subsequent occurrences of the substring.

@"(?<char>\w)\k<char>"

Alternation constructs modify a regular expression to enable either/or or conditional matching. .NET supports three alternation constructs:

  1. Pattern matching with |
  2. Conditional matching with (?(expression)yes|no)
  3. Conditional matching based on a valid captured group

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment