3 // namespace: System.Text.RegularExpressions
6 // author: Dan Lewis (dlewis@gmx.co.uk)
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections;
33 using System.Reflection;
34 using System.Reflection.Emit;
35 using System.Runtime.Serialization;
37 using RegularExpression = System.Text.RegularExpressions.Syntax.RegularExpression;
38 using Parser = System.Text.RegularExpressions.Syntax.Parser;
40 using System.Diagnostics;
43 namespace System.Text.RegularExpressions {
46 public partial class Regex : ISerializable {
49 private static int cache_size = 15;
53 public static void CompileToAssembly (RegexCompilationInfo [] regexes, AssemblyName aname)
55 Regex.CompileToAssembly(regexes, aname, new CustomAttributeBuilder [] {}, null);
59 public static void CompileToAssembly (RegexCompilationInfo [] regexes, AssemblyName aname,
60 CustomAttributeBuilder [] attribs)
62 Regex.CompileToAssembly(regexes, aname, attribs, null);
66 public static void CompileToAssembly (RegexCompilationInfo [] regexes, AssemblyName aname,
67 CustomAttributeBuilder [] attribs, string resourceFile)
69 throw new NotImplementedException ();
70 // TODO : Make use of attribs and resourceFile parameters
72 AssemblyBuilder asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.RunAndSave);
73 ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule("InnerRegexModule",aname.Name);
74 Parser psr = new Parser ();
76 System.Console.WriteLine("CompileToAssembly");
78 for(int i=0; i < regexes.Length; i++)
80 System.Console.WriteLine("Compiling expression :" + regexes[i].Pattern);
81 RegularExpression re = psr.ParseRegularExpression (regexes[i].Pattern, regexes[i].Options);
85 CILCompiler cmp = new CILCompiler (modBuilder, i);
86 bool reverse = (regexes[i].Options & RegexOptions.RightToLeft) !=0;
87 re.Compile (cmp, reverse);
93 // Define a runtime class with specified name and attributes.
94 TypeBuilder builder = modBuilder.DefineType("ITest");
96 asmBuilder.Save(aname.Name);
101 public static string Escape (string str)
103 return Parser.Escape (str);
106 public static string Unescape (string str)
108 return Parser.Unescape (str);
111 public static bool IsMatch (string input, string pattern)
113 return IsMatch (input, pattern, RegexOptions.None);
116 public static bool IsMatch (string input, string pattern, RegexOptions options)
118 Regex re = new Regex (pattern, options);
119 return re.IsMatch (input);
122 public static Match Match (string input, string pattern)
124 return Regex.Match (input, pattern, RegexOptions.None);
127 public static Match Match (string input, string pattern, RegexOptions options)
129 Regex re = new Regex (pattern, options);
130 return re.Match (input);
133 public static MatchCollection Matches (string input, string pattern)
135 return Matches (input, pattern, RegexOptions.None);
138 public static MatchCollection Matches (string input, string pattern, RegexOptions options)
140 Regex re = new Regex (pattern, options);
141 return re.Matches (input);
144 public static string Replace (string input, string pattern, MatchEvaluator evaluator)
146 return Regex.Replace (input, pattern, evaluator, RegexOptions.None);
149 public static string Replace (string input, string pattern, MatchEvaluator evaluator,
150 RegexOptions options)
152 Regex re = new Regex (pattern, options);
153 return re.Replace (input, evaluator);
156 public static string Replace (string input, string pattern, string replacement)
158 return Regex.Replace (input, pattern, replacement, RegexOptions.None);
161 public static string Replace (string input, string pattern, string replacement,
162 RegexOptions options)
164 Regex re = new Regex (pattern, options);
165 return re.Replace (input, replacement);
168 public static string [] Split (string input, string pattern)
170 return Regex.Split (input, pattern, RegexOptions.None);
173 public static string [] Split (string input, string pattern, RegexOptions options)
175 Regex re = new Regex (pattern, options);
176 return re.Split (input);
180 [MonoTODO ("should be used somewhere ? FactoryCache ?")]
181 public static int CacheSize {
182 get { return cache_size; }
185 throw new ArgumentOutOfRangeException ("CacheSize");
193 private static FactoryCache cache = new FactoryCache (200); // TODO put some meaningful number here
197 // This constructor is used by compiled regular expressions that are
198 // classes derived from Regex class. No initialization required.
203 public Regex (string pattern) : this (pattern, RegexOptions.None)
207 public Regex (string pattern, RegexOptions options)
209 this.pattern = pattern;
210 this.roptions = options;
216 this.machineFactory = cache.Lookup (this.pattern, this.roptions);
218 if (this.machineFactory == null) {
221 this.group_count = this.machineFactory.GroupCount;
222 this.mapping = this.machineFactory.Mapping;
223 this._groupNumberToNameMap = this.machineFactory.NamesMapping;
228 private void InitNewRegex ()
230 this.machineFactory = CreateMachineFactory (this.pattern, this.roptions);
231 this.group_count = machineFactory.GroupCount;
232 this.mapping = machineFactory.Mapping;
233 this._groupNumberToNameMap = this.machineFactory.NamesMapping;
236 private static IMachineFactory CreateMachineFactory (string pattern, RegexOptions options)
238 Parser psr = new Parser ();
239 RegularExpression re = psr.ParseRegularExpression (pattern, options);
242 //if ((options & RegexOptions.Compiled) != 0)
243 // //throw new Exception ("Not implemented.");
244 // cmp = new CILCompiler ();
246 cmp = new PatternCompiler ();
248 re.Compile (cmp, (options & RegexOptions.RightToLeft) != 0);
250 IMachineFactory machineFactory = cmp.GetMachineFactory ();
251 machineFactory.Mapping = psr.GetMapping ();
252 machineFactory.NamesMapping = GetGroupNamesArray (machineFactory.GroupCount, machineFactory.Mapping);
254 return machineFactory;
262 Regex (SerializationInfo info, StreamingContext context) :
263 this (info.GetString ("pattern"),
264 (RegexOptions) info.GetValue ("options", typeof (RegexOptions)))
268 #if ONLY_1_1 && !TARGET_JVM
269 // fixes public API signature
274 // public instance properties
276 public RegexOptions Options {
277 get { return roptions; }
280 public bool RightToLeft {
281 get { return (roptions & RegexOptions.RightToLeft) != 0; }
284 // public instance methods
286 public string [] GetGroupNames ()
288 string [] names = new string [mapping.Count];
289 mapping.Keys.CopyTo (names, 0);
294 public int[] GetGroupNumbers ()
296 int[] numbers = new int [mapping.Count];
297 mapping.Values.CopyTo (numbers, 0);
302 public string GroupNameFromNumber (int i)
304 if (i < 0 || i > group_count)
307 return _groupNumberToNameMap [i];
310 public int GroupNumberFromName (string name)
312 if (mapping.Contains (name))
313 return (int) mapping [name];
320 public bool IsMatch (string input)
322 return IsMatch (input, RightToLeft ? input.Length : 0);
325 public bool IsMatch (string input, int startat)
327 return Match (input, startat).Success;
330 public Match Match (string input)
332 return Match (input, RightToLeft ? input.Length : 0);
335 public Match Match (string input, int startat)
337 return CreateMachine ().Scan (this, input, startat, input.Length);
340 public Match Match (string input, int startat, int length)
342 return CreateMachine ().Scan (this, input, startat, startat + length);
345 public MatchCollection Matches (string input)
347 return Matches (input, RightToLeft ? input.Length : 0);
350 public MatchCollection Matches (string input, int startat)
352 Match m = Match (input, startat);
353 return new MatchCollection (m);
358 public string Replace (string input, MatchEvaluator evaluator)
360 return Replace (input, evaluator, Int32.MaxValue, RightToLeft ? input.Length : 0);
363 public string Replace (string input, MatchEvaluator evaluator, int count)
365 return Replace (input, evaluator, count, RightToLeft ? input.Length : 0);
370 public Adapter (MatchEvaluator ev) { this.ev = ev; }
371 public void Evaluate (Match m, StringBuilder sb) { sb.Append (ev (m)); }
374 public string Replace (string input, MatchEvaluator evaluator, int count, int startat)
376 BaseMachine m = (BaseMachine)CreateMachine ();
379 return m.RTLReplace (this, input, evaluator, count, startat);
381 // NOTE: If this is a cause of a lot of allocations, we can convert it to
382 // use a ThreadStatic allocation mitigator
383 Adapter a = new Adapter (evaluator);
385 return m.LTRReplace (this, input, new BaseMachine.MatchAppendEvaluator (a.Evaluate),
389 public string Replace (string input, string replacement)
391 return Replace (input, replacement, Int32.MaxValue, RightToLeft ? input.Length : 0);
394 public string Replace (string input, string replacement, int count)
396 return Replace (input, replacement, count, RightToLeft ? input.Length : 0);
399 public string Replace (string input, string replacement, int count, int startat)
401 return CreateMachine ().Replace (this, input, replacement, count, startat);
406 public string [] Split (string input)
408 return Split (input, Int32.MaxValue, RightToLeft ? input.Length : 0);
411 public string [] Split (string input, int count)
413 return Split (input, count, RightToLeft ? input.Length : 0);
416 public string [] Split (string input, int count, int startat)
418 return CreateMachine ().Split (this, input, count, startat);
421 // This method is called at the end of the constructor of compiled
422 // regular expression classes to do internal initialization.
423 protected void InitializeReferences ()
426 throw new NotSupportedException ("This operation is only allowed once per object.");
428 refsInitialized = true;
430 // Compile pattern that results in performance loss as existing
431 // CIL code is ignored but provides support for regular
432 // expressions compiled to assemblies.
436 protected bool UseOptionC ()
438 return ((roptions & RegexOptions.Compiled) != 0);
441 protected bool UseOptionR ()
443 return ((roptions & RegexOptions.RightToLeft) != 0);
448 public override string ToString ()
453 // ISerializable interface
454 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
456 info.AddValue ("pattern", this.ToString (), typeof (string));
457 info.AddValue ("options", this.Options, typeof (RegexOptions));
462 internal int GroupCount {
463 get { return group_count; }
468 private IMachine CreateMachine ()
470 return machineFactory.NewInstance ();
473 private static string [] GetGroupNamesArray (int groupCount, IDictionary mapping)
475 string [] groupNumberToNameMap = new string [groupCount + 1];
476 foreach (string name in mapping.Keys) {
477 groupNumberToNameMap [(int) mapping [name]] = name;
479 return groupNumberToNameMap;
482 private IMachineFactory machineFactory;
483 private IDictionary mapping;
484 private int group_count;
485 private bool refsInitialized;
486 private string [] _groupNumberToNameMap;
491 protected internal string pattern;
492 protected internal RegexOptions roptions;
494 // MS undocumented members
497 protected internal System.Collections.Generic.Dictionary<string, int> capnames;
499 protected internal System.Collections.Generic.Dictionary<int, int> caps;
502 protected internal System.Collections.Hashtable capnames;
504 protected internal System.Collections.Hashtable caps;
507 protected internal int capsize;
509 protected internal string [] capslist;
511 protected internal RegexRunnerFactory factory;