2 // System.Web.Services.Protocols.PatternMatcher.cs
\r
5 // Tim Coleman (tim@timcoleman.com)
\r
7 // Copyright (C) Tim Coleman, 2002
\r
10 using System.Web.Services;
\r
11 using System.Reflection;
\r
12 using System.Text.RegularExpressions;
\r
13 using System.Collections;
\r
15 namespace System.Web.Services.Protocols
\r
17 public sealed class PatternMatcher
\r
20 MatchInfo[] _matchInfos;
\r
22 public PatternMatcher (Type type)
\r
26 FieldInfo[] fields = type.GetFields ();
\r
27 ArrayList matchInfos = new ArrayList ();
\r
29 foreach (FieldInfo field in fields)
\r
31 object[] ats = field.GetCustomAttributes (typeof(MatchAttribute), true);
\r
32 if (ats.Length == 0) continue;
\r
34 MatchInfo mi = new MatchInfo ();
\r
36 mi.Match = (MatchAttribute) ats[0];
\r
38 RegexOptions opts = RegexOptions.Multiline;
\r
39 if (mi.Match.IgnoreCase) opts |= RegexOptions.IgnoreCase;
\r
40 mi.Regex = new Regex (mi.Match.Pattern, opts);
\r
42 matchInfos.Add (mi);
\r
44 _matchInfos = (MatchInfo[]) matchInfos.ToArray (typeof(MatchInfo));
\r
47 public object Match (string text)
\r
49 object ob = Activator.CreateInstance (_returnType);
\r
51 foreach (MatchInfo mi in _matchInfos)
\r
53 MatchCollection matches = mi.Regex.Matches (text);
\r
57 if (mi.Field.FieldType.IsArray)
\r
59 int max = mi.Match.MaxRepeats;
\r
60 if (max == -1) max = matches.Count;
\r
62 Type elemType = mi.Field.FieldType.GetElementType();
\r
63 Array array = Array.CreateInstance (elemType, max);
\r
64 for (int n=0; n<max; n++)
\r
65 array.SetValue (mi.GetMatchValue (matches[n], elemType), n);
\r
68 else if (matches.Count > 0)
\r
69 res = mi.GetMatchValue (matches[0], mi.Field.FieldType);
\r
71 mi.Field.SetValue (ob, res);
\r
80 public FieldInfo Field;
\r
81 public MatchAttribute Match;
\r
84 const string GroupError = "{0} is not a valid group index for match '{1}'. The highest valid group index for this match is {2}";
\r
85 const string CaptureError = "{0} is not a valid capture index for match '{1}'. The highest valid capture index for this match is {2}";
\r
87 public object GetMatchValue (Match match, Type castType)
\r
89 if (Match.Group >= match.Groups.Count)
\r
90 throw new Exception (string.Format (GroupError, Match.Group, Field.Name, match.Groups.Count-1));
\r
92 Group group = match.Groups [Match.Group];
\r
93 if (Match.Capture >= group.Captures.Count)
\r
94 throw new Exception (string.Format (CaptureError, Match.Capture, Field.Name, group.Captures.Count-1));
\r
96 string val = group.Captures [Match.Capture].Value;
\r
97 return Convert.ChangeType (val, castType);
\r