-2

I have regex patterns (about 100 or so) which are implemented using Regex class in C#. Now I want to give different weights when my input strings hit different patterns, for instances:

input_string = "xxxx... ";
weight=0.; 
Regex name_exp=new Rex("pe[t,e]er|j[o,0]hn|may|....");
if (name_exp.Match(input_string).Success==true);
 { 
       weight = ( 0.5 if it hits pe[t,e]er, 0.3 if it hits j[o,0]hn...) 
 }           

How do you design a program to do it in a better way, since I have 100 patterns, to list all of them is not very efficient. I am also thinking about using map. But can the map index be a regex ? Thanks

Mrk421
  • 5
  • 3
  • Aside: [This](http://stackoverflow.com/a/7707369/92546) may be helpful if you run into performance issues with multiple regex patterns. Or not. – HABO Jul 29 '16 at 20:24
  • You don't really want to match commas in the middle of the names (`Pe,er`, `j,hn`), do you? A comma has no special meaning in a character class. – Alan Moore Jul 29 '16 at 21:38
  • It's not quite clear what "in a better way" means here. Please try to specify your question. – YakovL Jul 29 '16 at 22:08

1 Answers1

1

You could make a class that has the pattern and the weight in it, do a loop on the instances, and apply the weight from the object

public class WeightedRegex
{
       public int Weight {get;set;}
       public Regex Regex {get;set;}
}

You don't need to check for the larger regex as if any of the individuals matched then it would have matched with the larger one

//in your method
//assuming you have a List of WeightedRegex called regexes 
var match = regexes.FirstOrDefault(a=>a.Regex.IsMatch(input_string));
if(match!=null)
{
    weight = match.Weight;
}
konkked
  • 3,161
  • 14
  • 19