Brandon Palmer
Brandon Palmer

Reputation: 313

Using RegularExpressions to Parse and Execute Method

I'm trying to write a mini-type scripting language for my service and I've been trying to extract data from certain strings in a line. For example:

!d3 Profile: {D3Api("Name")} !weather Current Weather {Weather("Location")}

Working with my current code, I cannot seem to get it to find the text I'm looking for. I can probably do an if statement if the line contains say {D3Api()} or {Weather()} right? Anyway, here's my expression for finding text {D3Api()} and retrieving the text in that:

String text = "Profile: (\\{D3Api\\(\"(.?)\"\\)\\})";
Regex r = new Regex(text , RegexOptions.IgnoreCase | RegexOptions.Singleline);

It's not parsing or returning the text. How can I improve this?

My poorly design parsing code:

public static void Main(string[] args) {
    string t = "{D3Api(\"Name\")";
    String text = "(\\{D3Api\\(\"(.*?)\"\\)\\})";
    Regex r = new Regex(text, RegexOptions.IgnoreCase | RegexOptions.Singleline);  
    Console.WriteLine("Parsing..\n\r");
    Match m = r.Match(t);
    if (m.Success) {
            string c = m.Groups[1].ToString();
            string s = m.Groups[2].ToString();
            Console.Write("(" + c.ToString() + ")" + "(" + s.ToString() + ")" + "\n");
    }
    Console.ReadLine();
}

Upvotes: 0

Views: 56

Answers (2)

jt000
jt000

Reputation: 3236

I'm not 100% sure if I'm actually answering your question, but I think your looking to have named groups. That is done with regex syntax like (?<function>[a-zA-Z0-9]+)\((?<param>[^)]\). With this you can set a generic format for your function names and take a single parameter. For more info on named groups take a look here.

As an aside, if your language is complex, then you may find that RegEx isn't robust enough for your needs. In this case, I'd suggest taking a look at creating a custom syntax using EBNF, then creating a tokenizer (pretty fun project IMO). An example of this can be seen here

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

You are not using quantifier. You can use * which means match the previous token 0 or more times.

String text = "(\\{D3Api\\(\"(.*?)\"\\)\\})";
Regex r = new Regex(text , RegexOptions.IgnoreCase | RegexOptions.Singleline);

After doing the above, you can do use Regex.Match or Matches if you want multiple matches.

Upvotes: 0

Related Questions