0

so i am writing a little toy compiler sort of thing in C#, and what i am trying to do is in the print command, for every substring that begins with the '$' character (eg - $foo), replace it with the appropriate variable. (basically, the '$' character indicates a variable name).

what i have done so far is to use regex to find all the substrings containing a '$' character, however i am having trouble with the replace method. How variables are stored is through the FLEE evaluator variable storage class. (FLEE being fast lightweight expression evaluator), they act as a map where the key is the variable name, and the value is the variable value.

my code is as follows:

        public void print(string exp)
    {
        this.expression = exp;
        MatchEvaluator eval = new MatchEvaluator(this.matchEval);
        MatchCollection coll = Regex.Matches(exp, @"(?<!\w)\$\w+");
        this.split = new string[coll.Count];
        int index = 0;
        foreach (Match match in coll)
        {
            this.split[index] = match.ToString();
            index++;
        }
        this.i = 0;
        Regex.Replace(exp, @"(?<!\w)\$\w+", eval);
        Console.WriteLine(exp);
        Console.ReadKey();
    }

    private string matchEval(Match m)
    {
        this.split[this.i] = this.split[this.i].TrimStart('$');
        if(i != split.Length-1)
            this.i++;
        return this.split[this.i];
    }

it doesn't return the variables yet, as it still returns the regex matches including the '$' character.

any help would be much appreciated, thanks.

1
  • 3
    Shouldn't it be: exp = Regex.Replace(exp, @"(?<!\w)\$\w+", eval); ? Commented Jan 6, 2012 at 8:31

1 Answer 1

1

As Marcel Valdez Orozco points out, the expression isn't the issue. The problem lies in the fact that you're expecting the String to be updated by the Regex.Replace call, but instead Regex.Replace returns a new String instance.

So update you code to take this into account:

exp = Regex.Replace(exp, @"(?<!\w)\$\w+", eval);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.