2
\$\begingroup\$

I use this method to extract table name and field name from formula.

public List<string> ExtractFieldsFromFormula(string formula)
{
 List<string> formulas = new List<string>();
 formulas.AddRange(formula.Split(new char[] {'{', '}'}).Where(f=>!f.Contains("+") && !f.Contains("-")&&!f.Contains("/")&&!f.Contains("*")&& !f.Contains("(")&& !f.Contains(")") && f.Trim()!=String.Empty));
 return formulas;
}

my formula is like this:

"{City.a}+5*(2/{City.b})"

and result of method is a list :

  • City.a
  • City.b

how can i write this code better than this?!!

asked Feb 26, 2012 at 19:53
\$\endgroup\$

2 Answers 2

7
\$\begingroup\$

And there's always a place for a regular expression (especially when searching for a pattern in a string of characters ;-)).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication9
{
 class Program
 {
 static void Main(string[] args)
 {
 string pattern = @"\{(?<expr>[a-zA-Z0-9.]+?)\}";
 string formula = @"{City.a}+5*(2/{City.b})";
 var matches = Regex.Matches(formula, pattern).OfType<Match>();
 foreach (var match in matches)
 {
 Console.WriteLine(match.Groups["expr"]);
 }
 // prints
 // City.a
 // City.b
 string splitPattern = @"\{(?<object>[a-zA-Z0-9]+?)\.(?<field>[a-zA-Z0-9]+?)\}";
 matches = Regex.Matches(formula, splitPattern).OfType<Match>();
 foreach (var match in matches)
 {
 Console.WriteLine("Object: {0} Field: {1}", match.Groups["object"], match.Groups["field"]);
 }
 // prints
 // Object: City Field: a
 // Object: City Field: b
 }
 }
}
answered Feb 26, 2012 at 20:47
\$\endgroup\$
1
  • \$\begingroup\$ Named matches?!? You made my day. \$\endgroup\$ Commented Feb 27, 2012 at 10:27
3
\$\begingroup\$

This should a) make it a bit more compact and b) be a bit faster.

 private static readonly char[] splitChars = new[] { '{', '}' };
 private static readonly char[] charsToExclude = new[] { '+', '-', '/', '*', '(', ')' };
 public static List<string> ExtractFieldsFromFormula(string formula)
 {
 var formulas = new List<string>();
 formulas.AddRange(formula.Split(splitChars).Where(f => (f.Trim().Length > 0) && (f.IndexOfAny(charsToExclude) == -1)));
 return formulas;
 }
answered Feb 26, 2012 at 20:19
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.