Skip to content

Instantly share code, notes, and snippets.

@kobi
Created Apr 25, 2011
Embed
What would you like to do?
Snippet for http://kobikobi.wordpress.com/2011/04/25/net-regular-expressions-using-the-stack-state-to-understand-numeric-values/ - capture a decimal number followed by the same number in binary base using nothing but regex and time.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
// sample for http://kobikobi.wordpress.com/2011/04/25/net-regular-expressions-using-the-stack-state-to-understand-numeric-values/
class Program
{
static void Main(string[] args)
{
string sampleText = "10:1010 3:11 4:100 4:101 5:101 1:1 1342:10100111110 1342:10100111111 1342:10100111101 0:0";
MatchCollection pairs = Regex.Matches(sampleText, DecimalNumberAndEqualBinaryNumber,
RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled);
foreach (Match match in pairs)
{
Console.WriteLine(match.Value);
}
Console.ReadKey();
}
public static readonly string DecimalNumberAndEqualBinaryNumber = @"
\b
(?>
(?=[0-9])
# multiply the content of the stack by 10
(?(Decimal)
(?<-Decimal>
(?<Temp>){10}
)
){100000}
(?(Decimal)(?!))
(?(Temp)
(?<-Temp>
(?<Decimal>)
)
){100000}
(?(Temp)(?!))
# match a digit, and push its value to the stack
(?:
0 |
1 (?<Decimal>) |
2 (?<Decimal>){2} |
3 (?<Decimal>){3} |
4 (?<Decimal>){4} |
5 (?<Decimal>){5} |
6 (?<Decimal>){6} |
7 (?<Decimal>){7} |
8 (?<Decimal>){8} |
9 (?<Decimal>){9}
)
)+
:
(?>
(?=[01])
# multiply the content of the stack by 2
(?(Binary)
(?<-Binary>
(?<Temp>){2}
)
){100000}
(?(Binary)(?!))
(?(Temp)
(?<-Temp>
(?<Binary>)
)
){100000}
(?(Temp)(?!))
# match a digit, and push its value to the stack
(?:
0 |
1 (?<Binary>)
)
)+
\b
# Check both stacks are the same length
(?(Decimal)
(?<-Decimal>)
(?<-Binary>)
){100000}
(?(Decimal)(?!))
(?(Binary)(?!))
";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment