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 |
227 #if MOBILE || !NET_2_1
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 |
239 #if MOBILE || !NET_2_1
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 seems to be working now, but
278 // potential problems are being tracked down here:
279 // https://bugzilla.novell.com/show_bug.cgi?id=470827
280 static readonly bool old_rx =
281 Environment.GetEnvironmentVariable ("MONO_NEW_RX") == null;
284 private static IMachineFactory CreateMachineFactory (string pattern, RegexOptions options)
286 Parser psr = new Parser ();
287 RegularExpression re = psr.ParseRegularExpression (pattern, options);
290 ICompiler cmp = new PatternCompiler ();
294 if ((options & RegexOptions.Compiled) != 0)
295 cmp = new CILCompiler ();
297 cmp = new RxCompiler ();
299 cmp = new PatternCompiler ();
303 re.Compile (cmp, (options & RegexOptions.RightToLeft) != 0);
305 IMachineFactory machineFactory = cmp.GetMachineFactory ();
306 Hashtable mapping = new Hashtable ();
307 machineFactory.Gap = psr.GetMapping (mapping);
308 machineFactory.Mapping = mapping;
309 machineFactory.NamesMapping = GetGroupNamesArray (machineFactory.GroupCount, machineFactory.Mapping);
311 return machineFactory;
319 Regex (SerializationInfo info, StreamingContext context) :
320 this (info.GetString ("pattern"),
321 (RegexOptions) info.GetValue ("options", typeof (RegexOptions)))
325 #if ONLY_1_1 && !TARGET_JVM
326 // fixes public API signature
331 // public instance properties
333 public RegexOptions Options {
334 get { return roptions; }
337 public bool RightToLeft {
338 get { return (roptions & RegexOptions.RightToLeft) != 0; }
341 // public instance methods
343 public string [] GetGroupNames ()
345 string [] names = new string [1 + group_count];
346 Array.Copy (group_names, names, 1 + group_count);
350 public int [] GetGroupNumbers ()
352 int [] numbers = new int [1 + group_count];
353 Array.Copy (GroupNumbers, numbers, 1 + group_count);
357 public string GroupNameFromNumber (int i)
359 i = GetGroupIndex (i);
363 return group_names [i];
366 public int GroupNumberFromName (string name)
368 if (!mapping.Contains (name))
370 int i = (int) mapping [name];
372 i = Int32.Parse (name);
376 internal int GetGroupIndex (int number)
380 if (gap > group_count)
382 return Array.BinarySearch (GroupNumbers, gap, group_count - gap + 1, number);
385 int default_startat (string input)
387 return (RightToLeft && input != null) ? input.Length : 0;
392 public bool IsMatch (string input)
394 return IsMatch (input, default_startat (input));
397 public bool IsMatch (string input, int startat)
399 return Match (input, startat).Success;
402 public Match Match (string input)
404 return Match (input, default_startat (input));
407 public Match Match (string input, int startat)
410 throw new ArgumentNullException ("input");
411 if (startat < 0 || startat > input.Length)
412 throw new ArgumentOutOfRangeException ("startat");
413 return CreateMachine ().Scan (this, input, startat, input.Length);
416 public Match Match (string input, int beginning, int length)
419 throw new ArgumentNullException ("input");
420 if (beginning < 0 || beginning > input.Length)
421 throw new ArgumentOutOfRangeException ("beginning");
422 if (length < 0 || length > input.Length - beginning)
423 throw new ArgumentOutOfRangeException ("length");
424 return CreateMachine ().Scan (this, input, beginning, beginning + length);
427 public MatchCollection Matches (string input)
429 return Matches (input, default_startat (input));
432 public MatchCollection Matches (string input, int startat)
434 Match m = Match (input, startat);
435 return new MatchCollection (m);
440 public string Replace (string input, MatchEvaluator evaluator)
442 return Replace (input, evaluator, Int32.MaxValue, default_startat (input));
445 public string Replace (string input, MatchEvaluator evaluator, int count)
447 return Replace (input, evaluator, count, default_startat (input));
452 public Adapter (MatchEvaluator ev) { this.ev = ev; }
453 public void Evaluate (Match m, StringBuilder sb) { sb.Append (ev (m)); }
456 public string Replace (string input, MatchEvaluator evaluator, int count, int startat)
459 throw new ArgumentNullException ("input");
460 if (evaluator == null)
461 throw new ArgumentNullException ("evaluator");
463 throw new ArgumentOutOfRangeException ("count");
464 if (startat < 0 || startat > input.Length)
465 throw new ArgumentOutOfRangeException ("startat");
467 BaseMachine m = (BaseMachine)CreateMachine ();
470 return m.RTLReplace (this, input, evaluator, count, startat);
472 // NOTE: If this is a cause of a lot of allocations, we can convert it to
473 // use a ThreadStatic allocation mitigator
474 Adapter a = new Adapter (evaluator);
476 return m.LTRReplace (this, input, new BaseMachine.MatchAppendEvaluator (a.Evaluate),
480 public string Replace (string input, string replacement)
482 return Replace (input, replacement, Int32.MaxValue, default_startat (input));
485 public string Replace (string input, string replacement, int count)
487 return Replace (input, replacement, count, default_startat (input));
490 public string Replace (string input, string replacement, int count, int startat)
493 throw new ArgumentNullException ("input");
494 if (replacement == null)
495 throw new ArgumentNullException ("replacement");
497 throw new ArgumentOutOfRangeException ("count");
498 if (startat < 0 || startat > input.Length)
499 throw new ArgumentOutOfRangeException ("startat");
501 return CreateMachine ().Replace (this, input, replacement, count, startat);
506 public string [] Split (string input)
508 return Split (input, Int32.MaxValue, default_startat (input));
511 public string [] Split (string input, int count)
513 return Split (input, count, default_startat (input));
516 public string [] Split (string input, int count, int startat)
519 throw new ArgumentNullException ("input");
521 throw new ArgumentOutOfRangeException ("count");
522 if (startat < 0 || startat > input.Length)
523 throw new ArgumentOutOfRangeException ("startat");
525 return CreateMachine ().Split (this, input, count, startat);
528 // This method is called at the end of the constructor of compiled
529 // regular expression classes to do internal initialization.
530 protected void InitializeReferences ()
533 throw new NotSupportedException ("This operation is only allowed once per object.");
535 refsInitialized = true;
537 // Compile pattern that results in performance loss as existing
538 // CIL code is ignored but provides support for regular
539 // expressions compiled to assemblies.
543 protected bool UseOptionC ()
545 return ((roptions & RegexOptions.Compiled) != 0);
548 protected bool UseOptionR ()
550 return ((roptions & RegexOptions.RightToLeft) != 0);
555 public override string ToString ()
560 // ISerializable interface
561 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
563 info.AddValue ("pattern", this.ToString (), typeof (string));
564 info.AddValue ("options", this.Options, typeof (RegexOptions));
569 internal int GroupCount {
570 get { return group_count; }
579 private IMachine CreateMachine ()
581 return machineFactory.NewInstance ();
584 private static string [] GetGroupNamesArray (int groupCount, IDictionary mapping)
586 string [] group_names = new string [groupCount + 1];
587 IDictionaryEnumerator de = mapping.GetEnumerator ();
588 while (de.MoveNext ())
589 group_names [(int) de.Value] = (string) de.Key;
593 private int [] GroupNumbers {
595 if (group_numbers == null) {
596 group_numbers = new int [1 + group_count];
597 for (int i = 0; i < gap; ++i)
598 group_numbers [i] = i;
599 for (int i = gap; i <= group_count; ++i)
600 group_numbers [i] = Int32.Parse (group_names [i]);
601 return group_numbers;
603 return group_numbers;
607 private IMachineFactory machineFactory;
608 private IDictionary mapping;
609 private int group_count;
611 private bool refsInitialized;
612 private string [] group_names;
613 private int [] group_numbers;
617 protected internal string pattern;
618 protected internal RegexOptions roptions;
620 // MS undocumented members
623 internal System.Collections.Generic.Dictionary<string, int> capnames;
625 internal System.Collections.Generic.Dictionary<int, int> caps;
628 protected internal System.Collections.Hashtable capnames;
630 protected internal System.Collections.Hashtable caps;
633 protected internal RegexRunnerFactory factory;
636 protected internal int capsize;
638 protected internal string [] capslist;