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 {
50 public static void CompileToAssembly (RegexCompilationInfo [] regexes, AssemblyName aname)
52 Regex.CompileToAssembly(regexes, aname, new CustomAttributeBuilder [] {}, null);
56 public static void CompileToAssembly (RegexCompilationInfo [] regexes, AssemblyName aname,
57 CustomAttributeBuilder [] attribs)
59 Regex.CompileToAssembly(regexes, aname, attribs, null);
63 public static void CompileToAssembly (RegexCompilationInfo [] regexes, AssemblyName aname,
64 CustomAttributeBuilder [] attribs, string resourceFile)
66 throw new NotImplementedException ();
67 // TODO : Make use of attribs and resourceFile parameters
69 AssemblyBuilder asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly (aname, AssemblyBuilderAccess.RunAndSave);
70 ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule("InnerRegexModule",aname.Name);
71 Parser psr = new Parser ();
73 System.Console.WriteLine("CompileToAssembly");
75 for(int i=0; i < regexes.Length; i++)
77 System.Console.WriteLine("Compiling expression :" + regexes[i].Pattern);
78 RegularExpression re = psr.ParseRegularExpression (regexes[i].Pattern, regexes[i].Options);
82 CILCompiler cmp = new CILCompiler (modBuilder, i);
83 bool reverse = (regexes[i].Options & RegexOptions.RightToLeft) !=0;
84 re.Compile (cmp, reverse);
90 // Define a runtime class with specified name and attributes.
91 TypeBuilder builder = modBuilder.DefineType("ITest");
93 asmBuilder.Save(aname.Name);
98 public static string Escape (string str)
101 throw new ArgumentNullException ("str");
102 return Parser.Escape (str);
105 public static string Unescape (string str)
108 throw new ArgumentNullException ("str");
109 return Parser.Unescape (str);
112 public static bool IsMatch (string input, string pattern)
114 return IsMatch (input, pattern, RegexOptions.None);
117 public static bool IsMatch (string input, string pattern, RegexOptions options)
119 Regex re = new Regex (pattern, options);
120 return re.IsMatch (input);
123 public static Match Match (string input, string pattern)
125 return Regex.Match (input, pattern, RegexOptions.None);
128 public static Match Match (string input, string pattern, RegexOptions options)
130 Regex re = new Regex (pattern, options);
131 return re.Match (input);
134 public static MatchCollection Matches (string input, string pattern)
136 return Matches (input, pattern, RegexOptions.None);
139 public static MatchCollection Matches (string input, string pattern, RegexOptions options)
141 Regex re = new Regex (pattern, options);
142 return re.Matches (input);
145 public static string Replace (string input, string pattern, MatchEvaluator evaluator)
147 return Regex.Replace (input, pattern, evaluator, RegexOptions.None);
150 public static string Replace (string input, string pattern, MatchEvaluator evaluator,
151 RegexOptions options)
153 Regex re = new Regex (pattern, options);
154 return re.Replace (input, evaluator);
157 public static string Replace (string input, string pattern, string replacement)
159 return Regex.Replace (input, pattern, replacement, RegexOptions.None);
162 public static string Replace (string input, string pattern, string replacement,
163 RegexOptions options)
165 Regex re = new Regex (pattern, options);
166 return re.Replace (input, replacement);
169 public static string [] Split (string input, string pattern)
171 return Regex.Split (input, pattern, RegexOptions.None);
174 public static string [] Split (string input, string pattern, RegexOptions options)
176 Regex re = new Regex (pattern, options);
177 return re.Split (input);
181 static FactoryCache cache = new FactoryCache (15);
182 public static int CacheSize {
183 get { return cache.Capacity; }
186 throw new ArgumentOutOfRangeException ("CacheSize");
188 cache.Capacity = value;
192 static FactoryCache cache = new FactoryCache (200);
200 // This constructor is used by compiled regular expressions that are
201 // classes derived from Regex class. No initialization required.
206 public Regex (string pattern) : this (pattern, RegexOptions.None)
210 public Regex (string pattern, RegexOptions options)
213 throw new ArgumentNullException ("pattern");
214 validate_options (options);
215 this.pattern = pattern;
216 this.roptions = options;
220 static void validate_options (RegexOptions options)
222 const RegexOptions allopts =
224 RegexOptions.IgnoreCase |
225 RegexOptions.Multiline |
226 RegexOptions.ExplicitCapture |
228 RegexOptions.Compiled |
230 RegexOptions.Singleline |
231 RegexOptions.IgnorePatternWhitespace |
232 RegexOptions.RightToLeft |
233 RegexOptions.ECMAScript |
234 RegexOptions.CultureInvariant;
236 const RegexOptions ecmaopts =
237 RegexOptions.IgnoreCase |
238 RegexOptions.Multiline |
240 RegexOptions.Compiled |
242 RegexOptions.ECMAScript;
244 if ((options & ~allopts) != 0)
245 throw new ArgumentOutOfRangeException ("options");
246 if ((options & RegexOptions.ECMAScript) != 0 && (options & ~ecmaopts) != 0)
247 throw new ArgumentOutOfRangeException ("options");
253 this.machineFactory = cache.Lookup (this.pattern, this.roptions);
255 if (this.machineFactory == null) {
258 this.group_count = this.machineFactory.GroupCount;
259 this.gap = this.machineFactory.Gap;
260 this.mapping = this.machineFactory.Mapping;
261 this.group_names = this.machineFactory.NamesMapping;
266 private void InitNewRegex ()
268 this.machineFactory = CreateMachineFactory (this.pattern, this.roptions);
269 cache.Add (this.pattern, this.roptions, this.machineFactory);
270 this.group_count = machineFactory.GroupCount;
271 this.gap = this.machineFactory.Gap;
272 this.mapping = machineFactory.Mapping;
273 this.group_names = this.machineFactory.NamesMapping;
277 // The new rx engine has blocking bugs like
278 // https://bugzilla.novell.com/show_bug.cgi?id=470827
279 static readonly bool old_rx =
280 Environment.GetEnvironmentVariable ("MONO_NEW_RX") == null;
283 private static IMachineFactory CreateMachineFactory (string pattern, RegexOptions options)
285 Parser psr = new Parser ();
286 RegularExpression re = psr.ParseRegularExpression (pattern, options);
289 ICompiler cmp = new PatternCompiler ();
293 if ((options & RegexOptions.Compiled) != 0)
294 cmp = new CILCompiler ();
296 cmp = new RxCompiler ();
298 cmp = new PatternCompiler ();
302 re.Compile (cmp, (options & RegexOptions.RightToLeft) != 0);
304 IMachineFactory machineFactory = cmp.GetMachineFactory ();
305 Hashtable mapping = new Hashtable ();
306 machineFactory.Gap = psr.GetMapping (mapping);
307 machineFactory.Mapping = mapping;
308 machineFactory.NamesMapping = GetGroupNamesArray (machineFactory.GroupCount, machineFactory.Mapping);
310 return machineFactory;
318 Regex (SerializationInfo info, StreamingContext context) :
319 this (info.GetString ("pattern"),
320 (RegexOptions) info.GetValue ("options", typeof (RegexOptions)))
324 #if ONLY_1_1 && !TARGET_JVM
325 // fixes public API signature
330 // public instance properties
332 public RegexOptions Options {
333 get { return roptions; }
336 public bool RightToLeft {
337 get { return (roptions & RegexOptions.RightToLeft) != 0; }
340 // public instance methods
342 public string [] GetGroupNames ()
344 string [] names = new string [1 + group_count];
345 Array.Copy (group_names, names, 1 + group_count);
349 public int [] GetGroupNumbers ()
351 int [] numbers = new int [1 + group_count];
352 Array.Copy (GroupNumbers, numbers, 1 + group_count);
356 public string GroupNameFromNumber (int i)
358 i = GetGroupIndex (i);
362 return group_names [i];
365 public int GroupNumberFromName (string name)
367 if (!mapping.Contains (name))
369 int i = (int) mapping [name];
371 i = Int32.Parse (name);
375 internal int GetGroupIndex (int number)
379 if (gap > group_count)
381 return Array.BinarySearch (GroupNumbers, gap, group_count - gap + 1, number);
384 int default_startat (string input)
386 return (RightToLeft && input != null) ? input.Length : 0;
391 public bool IsMatch (string input)
393 return IsMatch (input, default_startat (input));
396 public bool IsMatch (string input, int startat)
398 return Match (input, startat).Success;
401 public Match Match (string input)
403 return Match (input, default_startat (input));
406 public Match Match (string input, int startat)
409 throw new ArgumentNullException ("input");
410 if (startat < 0 || startat > input.Length)
411 throw new ArgumentOutOfRangeException ("startat");
412 return CreateMachine ().Scan (this, input, startat, input.Length);
415 public Match Match (string input, int startat, int length)
418 throw new ArgumentNullException ("input");
419 if (startat < 0 || startat > input.Length)
420 throw new ArgumentOutOfRangeException ("startat");
421 if (length < 0 || length > input.Length - startat)
422 throw new ArgumentOutOfRangeException ("length");
423 return CreateMachine ().Scan (this, input, startat, startat + length);
426 public MatchCollection Matches (string input)
428 return Matches (input, default_startat (input));
431 public MatchCollection Matches (string input, int startat)
433 Match m = Match (input, startat);
434 return new MatchCollection (m);
439 public string Replace (string input, MatchEvaluator evaluator)
441 return Replace (input, evaluator, Int32.MaxValue, default_startat (input));
444 public string Replace (string input, MatchEvaluator evaluator, int count)
446 return Replace (input, evaluator, count, default_startat (input));
451 public Adapter (MatchEvaluator ev) { this.ev = ev; }
452 public void Evaluate (Match m, StringBuilder sb) { sb.Append (ev (m)); }
455 public string Replace (string input, MatchEvaluator evaluator, int count, int startat)
458 throw new ArgumentNullException ("input");
459 if (evaluator == null)
460 throw new ArgumentNullException ("evaluator");
462 throw new ArgumentOutOfRangeException ("count");
463 if (startat < 0 || startat > input.Length)
464 throw new ArgumentOutOfRangeException ("startat");
466 BaseMachine m = (BaseMachine)CreateMachine ();
469 return m.RTLReplace (this, input, evaluator, count, startat);
471 // NOTE: If this is a cause of a lot of allocations, we can convert it to
472 // use a ThreadStatic allocation mitigator
473 Adapter a = new Adapter (evaluator);
475 return m.LTRReplace (this, input, new BaseMachine.MatchAppendEvaluator (a.Evaluate),
479 public string Replace (string input, string replacement)
481 return Replace (input, replacement, Int32.MaxValue, default_startat (input));
484 public string Replace (string input, string replacement, int count)
486 return Replace (input, replacement, count, default_startat (input));
489 public string Replace (string input, string replacement, int count, int startat)
492 throw new ArgumentNullException ("input");
493 if (replacement == null)
494 throw new ArgumentNullException ("replacement");
496 throw new ArgumentOutOfRangeException ("count");
497 if (startat < 0 || startat > input.Length)
498 throw new ArgumentOutOfRangeException ("startat");
500 return CreateMachine ().Replace (this, input, replacement, count, startat);
505 public string [] Split (string input)
507 return Split (input, Int32.MaxValue, default_startat (input));
510 public string [] Split (string input, int count)
512 return Split (input, count, default_startat (input));
515 public string [] Split (string input, int count, int startat)
518 throw new ArgumentNullException ("input");
520 throw new ArgumentOutOfRangeException ("count");
521 if (startat < 0 || startat > input.Length)
522 throw new ArgumentOutOfRangeException ("startat");
524 return CreateMachine ().Split (this, input, count, startat);
527 // This method is called at the end of the constructor of compiled
528 // regular expression classes to do internal initialization.
529 protected void InitializeReferences ()
532 throw new NotSupportedException ("This operation is only allowed once per object.");
534 refsInitialized = true;
536 // Compile pattern that results in performance loss as existing
537 // CIL code is ignored but provides support for regular
538 // expressions compiled to assemblies.
542 protected bool UseOptionC ()
544 return ((roptions & RegexOptions.Compiled) != 0);
547 protected bool UseOptionR ()
549 return ((roptions & RegexOptions.RightToLeft) != 0);
554 public override string ToString ()
559 // ISerializable interface
560 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
562 info.AddValue ("pattern", this.ToString (), typeof (string));
563 info.AddValue ("options", this.Options, typeof (RegexOptions));
568 internal int GroupCount {
569 get { return group_count; }
578 private IMachine CreateMachine ()
580 return machineFactory.NewInstance ();
583 private static string [] GetGroupNamesArray (int groupCount, IDictionary mapping)
585 string [] group_names = new string [groupCount + 1];
586 IDictionaryEnumerator de = mapping.GetEnumerator ();
587 while (de.MoveNext ())
588 group_names [(int) de.Value] = (string) de.Key;
592 private int [] GroupNumbers {
594 if (group_numbers == null) {
595 group_numbers = new int [1 + group_count];
596 for (int i = 0; i < gap; ++i)
597 group_numbers [i] = i;
598 for (int i = gap; i <= group_count; ++i)
599 group_numbers [i] = Int32.Parse (group_names [i]);
600 return group_numbers;
602 return group_numbers;
606 private IMachineFactory machineFactory;
607 private IDictionary mapping;
608 private int group_count;
610 private bool refsInitialized;
611 private string [] group_names;
612 private int [] group_numbers;
616 protected internal string pattern;
617 protected internal RegexOptions roptions;
619 // MS undocumented members
622 internal System.Collections.Generic.Dictionary<string, int> capnames;
624 internal System.Collections.Generic.Dictionary<int, int> caps;
627 protected internal System.Collections.Hashtable capnames;
629 protected internal System.Collections.Hashtable caps;
632 protected internal RegexRunnerFactory factory;
635 protected internal int capsize;
637 protected internal string [] capslist;