Last active
January 5, 2021 01:00
-
-
Save JerryNixon/1571cf101517fae62786538b778a10b2 to your computer and use it in GitHub Desktop.
Balance Parentheses in a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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}"); | |
| } | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
|(?(expression)yes|no)