I had to write an infix to prefix converter and figured I'd finally get down and learn how to use regex. I know there are much more popular ways (stacks, binary tree), but I didn't want to look anything up before doing the assignment 
What I really like about it though is that the line I've commented is all you need to change the entire operation of the algorithm. It not only populates what the operators to search for are, but it also controls order of operations, so if for some unknown reason you want to deviate from PEMDAS, you go right ahead. It's also only 51 lines long
The regex pattern itself looks like hell I know, it took me on and off work for 12 hours to get it tweaked just right, but I'm 99% sure it's bullet proof.
Just figured I'd post it here for posterity's sake, as having searched around I couldn't find anyone who'd done something similar!
Programmed in C#.
Edited by crazyap7 - 4/9/12 at 2:37pm

What I really like about it though is that the line I've commented is all you need to change the entire operation of the algorithm. It not only populates what the operators to search for are, but it also controls order of operations, so if for some unknown reason you want to deviate from PEMDAS, you go right ahead. It's also only 51 lines long

The regex pattern itself looks like hell I know, it took me on and off work for 12 hours to get it tweaked just right, but I'm 99% sure it's bullet proof.
Just figured I'd post it here for posterity's sake, as having searched around I couldn't find anyone who'd done something similar!
Programmed in C#.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ACSL_4_SR
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Infix to Prefix Converter");
Console.WriteLine("");
while (true == true)
{
Console.WriteLine("Input infix operation:");
string infix_input = Console.ReadLine();
string converted = convertToPrefix(infix_input);
Console.WriteLine(converted.Replace("(", "").Replace(")", ""));
}
}
static String convertToPrefix(string infix_input)
{
char[] operators = new char[4] { '*', '/', '+', '-' }; // Order of operations and operators
for (int i = 0; i <= operators.Length - 1; i++)
{
string pattern = @"([A-Z]+|(?<![A-Z])[\*\-\+]*\((?:[^()]|(?<OPEN>\()|(?<-OPEN>\)))+(?(OPEN)(?!))\))\" + operators[i] + @"([\*\-\+]*[A-Z]|\(.*\))";
Regex pairs = new Regex(pattern, RegexOptions.IgnoreCase);
Match m = pairs.Match(infix_input);
while (m.Success)
{
Group g = m.Groups[1];
CaptureCollection cc = g.Captures;
Capture c = cc[0];
infix_input = infix_input.Insert(c.Index, "(" + operators[i].ToString());
infix_input = infix_input.Remove(c.Index + g.Length + 2, 1);
g = m.Groups[2];
cc = g.Captures;
c = cc[0];
infix_input = infix_input.Insert(c.Index + g.Length + 1, ")");
m = pairs.Match(infix_input);
}
}
return infix_input;
}
}
}
Edited by crazyap7 - 4/9/12 at 2:37pm







