Example #1
2
        //public static void Test_Regex(string sRegex, string sInput)
        //{
        //    Test_Regex(sRegex, sInput, RegexOptions.Compiled | RegexOptions.IgnoreCase);
        //}

        public static void Test(string regexPattern, string text, RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase)
        {
            Regex regex = new Regex(regexPattern, options);
            Trace.WriteLine("Regex     : {0}", regexPattern);
            Trace.WriteLine("Input     : {0}", text);
            Match match = regex.Match(text);
            //string s;
            //if (match.Success) s = "found"; else s = "not found";
            //Trace.WriteLine("Result    : {0}", s);
            if (!match.Success)
                Trace.WriteLine("Result    : not found");
            int n = 1;
            while (match.Success)
            {
                Trace.WriteLine("Result    : found no {0}", n++);
                for (int i = 0; i < match.Groups.Count; i++)
                {
                    Trace.WriteLine("Groups[{0}] : \"{1}\"", i, match.Groups[i].Value);
                    if (match.Groups[i].Captures.Count > 1)
                    {
                        for (int j = 0; j < match.Groups[i].Captures.Count; j++)
                        {
                            Trace.WriteLine(" Capture[{0}] : \"{1}\"", j, match.Groups[i].Captures[j]);
                        }
                    }
                }
                match = match.NextMatch();
            }
        }
Example #2
0
        void ids_BeginRequest(object sender, EventArgs e)
        {
            //Attempt to read the app's config
            IDSGlobalSettings ims = (IDSGlobalSettings)ConfigurationSettings.GetConfig("dotnetids/idsconfig");

            string filename = System.IO.Path.GetFileName(HttpContext.Current.Request.Url.AbsolutePath).ToLowerInvariant();

            //Look for regex options to exclude
            foreach (RegexSettings rs in ims.ExcludedRegexen)
            {
                RegexOptions ro = new RegexOptions();

                if (rs.IgnoreCase)
                {
                    ro = ro | RegexOptions.IgnoreCase;
                }
                
                if (Regex.IsMatch(HttpContext.Current.Request.Url.AbsolutePath, rs.Pattern, ro)) return;
            }

            //Look for pages to exclude
            foreach (string s in ims.ExcludedPages)
            {
                if (s.ToLowerInvariant() == filename) return;
            }

            //Run the scanner
            WebScanRunner sr = new WebScanRunner(ims);
            sr.Run();
        }
        /// <summary>
        /// Creates the regex options.
        /// </summary>
        /// <returns>RegexOptions</returns>
        private RegexOptions CreateRegexOptions()
        {
            RegexOptions regOp = new RegexOptions();
            if (this.checkedListBoxOptions.CheckedItems.Contains("Ignore whitespace"))
            {
                regOp |= RegexOptions.IgnorePatternWhitespace;
            }

            if (this.checkedListBoxOptions.CheckedItems.Contains("Ignore case"))
            {
                regOp |= RegexOptions.IgnoreCase;
            }

            if (this.checkedListBoxOptions.CheckedItems.Contains("Explicit capture"))
            {
                regOp |= RegexOptions.ExplicitCapture;
            }

            if (this.checkedListBoxOptions.CheckedItems.Contains("Singleline"))
            {
                regOp |= RegexOptions.Singleline;
            }

            if (this.checkedListBoxOptions.CheckedItems.Contains("Multiline"))
            {
                regOp |= RegexOptions.Multiline;
            }

            if (this.checkedListBoxOptions.CheckedItems.Contains("Right to left"))
            {
                regOp |= RegexOptions.RightToLeft;
            }

            return regOp;
        }
Example #4
0
        /// <summary>
        /// Parse string settings
        /// </summary>
        /// <param name="list">string settings</param>
        /// <param name="options">reg ex options</param>
        /// <param name="isFirstMatch"></param>
        public static void RegexOptionsParse(string list, ref RegexOptions options, ref bool isFirstMatch)
        {
            List<string> unknownParameters = null;

            foreach (var value in list.Split('|').Where(i=>!string.IsNullOrEmpty(i)).ToArray())
            {
                try
                {
                    // parse regex options
                    options |= (RegexOptions) Enum.Parse(typeof (RegexOptions), value, true);
                }

                catch (ArgumentException)
                {
                    // other options
                    switch (value.ToUpper().Trim())
                    {
                        case "FIRSTMATCH":
                            isFirstMatch = true;
                            break;

                        default:
                            unknownParameters = new List<string> {value};
                            break;
                    }
                }
            }

            // unknown agument axception
            if (unknownParameters != null)
            {
                throw new ArgumentException(string.Format("Unknown parameters ({0})", string.Join(",", unknownParameters.ToArray())));
            }

        }
Example #5
0
        /// <summary>
        ///     Gets whether a <see cref="Regex" /> with the specified pattern finds a match in the specified input
        ///     <see cref="String" />.
        /// </summary>
        /// <exception cref="ArgumentNullException">The input can not be null.</exception>
        /// <exception cref="ArgumentNullException">The pattern can not be null.</exception>
        /// <exception cref="ArgumentNullException">The timeout can not be null.</exception>
        /// <param name="input">The <see cref="String" /> to search for a match.</param>
        /// <param name="pattern">The regular expression pattern used by the <see cref="Regex" />.</param>
        /// <param name="options">The regular expression options used by the <see cref="Regex" />.</param>
        /// <param name="timeOut">The timeout for the match operation.</param>
        /// <returns>A value of true if the regular expression finds a match, otherwise false.</returns>
        public static Boolean IsMatch( this String input, String pattern, RegexOptions options, TimeSpan timeOut )
        {
            input.ThrowIfNull( nameof( input ) );
            pattern.ThrowIfNull( nameof( pattern ) );

            return Regex.IsMatch( input, pattern, options, timeOut );
        }
Example #6
0
        /*
         * This static call constructs a RegexTree from a regular expression
         * pattern string and an option string.
         *
         * The method creates, drives, and drops a parser instance.
         */
        internal static RegexTree Parse(string re, RegexOptions op)
        {
            int end;
            var pcreOptions = TrimPcreRegexOption(re, out end);
            var pattern = TrimDelimiters(re, end);

            RegexParser p;
            RegexNode root;
            string[] capnamelist;

            p = new RegexParser((op & RegexOptions.CultureInvariant) != 0 ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture);

            p._options = op;

            p.SetPattern(pattern);
            p.CountCaptures();
            p.Reset(op);
            root = p.ScanRegex();

            if (p._capnamelist == null)
                capnamelist = null;
            else
                capnamelist = p._capnamelist.ToArray();

            return new RegexTree(root, p._caps, p._capnumlist, p._captop, p._capnames, capnamelist, op);
        }
Example #7
0
        public static void IsMatch(string pattern, string input, RegexOptions options = RegexOptions.None)
        {
            var rx = new Regex(pattern, options);
            var isMatch = rx.IsMatch(input);

            Assert.IsTrue(isMatch, "Failed to match input '{0}' against pattern '{1}'", input, pattern);
        }
Example #8
0
 private RegexAttribute(string pattern, RegexOptions options, bool optionsSpecified, Type compiledRegexType)
 {
     this.pattern = pattern;
     this.options = options;
     this.optionsSpecified = optionsSpecified;
     this.compiledRegexType = compiledRegexType;
 }
 public PhoneRegex(String pattern, RegexOptions options)
     : base(pattern, options)
 {
     var o = options | Redirections.Compiled;
     allRegex_ = new Regex(String.Format("^(?:{0})$", pattern), o);
     beginRegex_ = new Regex(String.Format("^(?:{0})", pattern), o);
 }
        /// <summary>
        /// Primary constructor.
        /// </summary>
        /// <param name="pattern">The regular expression pattern to match
        /// against.</param>
        public MustNotMatchRegexAttribute(string pattern)
        {
            Pattern = pattern;
            _options = RegexOptions.None;

            _regEx = new Regex(pattern, _options);
        }
Example #11
0
 ///<summary>Return the contents of a string up to the first match of a regular expression</summary>
 public static string SubstringBefore(this string str, string regex, RegexOptions? options = null)
 {
     var match = options.HasValue ? Regex.Match(str, regex, options.Value) : Regex.Match(str, regex);
     if (!match.Success) return str;
     var index = match.Index;
     return str.Substring(0, index);
 }
		public string Reformat (RegexOptions options,
			string reformattedPattern,
			PatternGrouping patternGrouping) {
			if (!HasConstruct (reformattedPattern, options)) {
				return reformattedPattern;
			}

			if (patternGrouping.GroupCount >= 0 && patternGrouping.SameGroupsFlag) {
				return null;
			}

			Matcher m = JavaUtils.Matcher (reformattedPattern, NUMBER_BACK_REFERENCE_PATTERN);
			if (m.find ()) {
				reformattedPattern = ReplaceGroupNumber (m, reformattedPattern, patternGrouping, options);
				if (reformattedPattern == null)
					return null;
			}

			m = JavaUtils.Matcher(reformattedPattern, NAME_1_BACK_REFERENCE_PATTERN);
			if (m.find ()) {
				reformattedPattern = ReplaceGroupName (m, reformattedPattern, patternGrouping, options);
				if (reformattedPattern == null)
					return null;
			}

			m = JavaUtils.Matcher(reformattedPattern, NAME_2_BACK_REFERENCE_PATTERN);
			if (m.find ()) {
				reformattedPattern = ReplaceGroupName (m, reformattedPattern, patternGrouping, options);
				if (reformattedPattern == null)
					return null;
			}

			return reformattedPattern;
		}
Example #13
0
 private ParamCollection Parse(ref string s, string pattern, bool remove, string tag, RegexOptions options)
 {
     ParamCollection cmd = new ParamCollection(Name);
     Regex rex = new Regex(pattern, options);
     Match m1 = rex.Match(s);
     while (m1.Success)
     {
         string param = m1.Groups[PARAM].Value;
         string arg = m1.Groups[ARGS].Value;
         if (param != null)
         {
             param = param.TrimEnd(' ');
             ArgCollection prm = cmd.Add(param, new ArgCollection(param, tag));
             if (arg != null)
             {
                 arg = arg.TrimEnd(' ');
                 if (!string.IsNullOrEmpty(arg))
                 {
                     prm.Add(arg);
                 }
             }
         }
         if (remove)
         {
             s = s.Remove(m1.Index, m1.Length).Trim();
             m1 = rex.Match(s);
         }
         else
         {
             m1 = rex.Match(s, m1.Index + m1.Length);
         }
     }
     return cmd;
 }
 /// <devdoc>
 ///    <para>
 ///       [To be supplied]
 ///    </para>
 /// </devdoc>
 public RegexCompilationInfo(String pattern, RegexOptions options, String name, String fullnamespace, bool ispublic) {
     Pattern = pattern;
     Name = name;
     Namespace = fullnamespace;
     this.options = options;
     isPublic = ispublic;
 }
        public RegexConstraint(string parameterName, string pattern, RegexOptions options)
        {
            Precondition.Defined(parameterName, () => Error.ArgumentNull("parameterName"));

            _parameterName = parameterName;
            _pattern = new Regex(NormalizePattern(pattern), options);
        }
Example #16
0
 private static string GetValueFromText(string text, string regex, RegexOptions option = RegexOptions.None)
 {
     MatchCollection mat = Regex.Matches(text, regex, option);
     if (mat.Count > 0)
         return mat[0].Groups["token"].ToString().Trim(trimChars: new char[] { ' ' });
     return string.Empty;
 }
Example #17
0
       RegexOptions AddOptions ( RegexOptions options ){
	       if( Compiled ){
		       options |= RegexOptions.Compiled;
	       }

	       return options;
       }
        public VerbalExpressions AddModifier(char modifier)
        {
            switch (modifier)
            {
                //case 'd':
                //	_modifiers |= RegexOptions.UNIX_LINES;
                //	break;
                case 'i':
                    _modifiers |= RegexOptions.IgnoreCase;
                    break;
                case 'x':
                    _modifiers |= RegexOptions.IgnorePatternWhitespace;
                    break;
                case 'm':
                    _modifiers |= RegexOptions.Multiline;
                    break;
                //case 's':
                //	_modifiers |= RegexOptions.DOTALL;
                //	break;
                //case 'u':
                //	_modifiers |= Pattern.UNICODE_CASE;
                //	break;
                //case 'U':
                //	_modifiers |= Pattern.UNICODE_CHARACTER_CLASS;
                //	break;
            }

            return this;
        }
Example #19
0
 public void Split(string pattern, string input, RegexOptions options, int count, int start, string[] expected)
 {
     bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, start);
     bool isDefaultCount = RegexHelpers.IsDefaultStart(input, options, count);
     if (options == RegexOptions.None)
     {
         // Use Split(string), Split(string, string), Split(string, int) or Split(string, int, int)
         if (isDefaultStart && isDefaultCount)
         {
             // Use Split(string) or Split(string, string)
             Assert.Equal(expected, new Regex(pattern).Split(input));
             Assert.Equal(expected, Regex.Split(input, pattern));
         }
         if (isDefaultStart)
         {
             // Use Split(string, int)
             Assert.Equal(expected, new Regex(pattern).Split(input, count));
         }
         // Use Split(string, int, int)
         Assert.Equal(expected, new Regex(pattern).Split(input, count, start));
     }
     if (isDefaultStart && isDefaultCount)
     {
         // Use Split(string, string, RegexOptions)
         Assert.Equal(expected, Regex.Split(input, pattern, options));
     }
     if (isDefaultStart)
     {
         // Use Split(string, int)
         Assert.Equal(expected, new Regex(pattern, options).Split(input, count));
     }
     // Use Split(string, int, int, int)
     Assert.Equal(expected, new Regex(pattern, options).Split(input, count, start));
 }
Example #20
0
        /// <summary>
        /// Writes the code to string in the specific language
        /// and returns the string
        /// </summary>
        public static string Create(Language language, string expression, RegexOptions options)
        {
            CodeCompileUnit unit = Create(expression, options);

            System.Text.StringBuilder builder = new System.Text.StringBuilder();

            using (System.IO.StringWriter stringWriter = new System.IO.StringWriter(builder))
            {
                System.CodeDom.Compiler.ICodeGenerator generator;

                switch (language)
                {
                    case Language.CSharp:
                        System.CodeDom.Compiler.CodeGeneratorOptions genOptions = new System.CodeDom.Compiler.CodeGeneratorOptions();
                        genOptions.BracingStyle = "C";
                        generator = new Microsoft.CSharp.CSharpCodeProvider().CreateGenerator();
                        generator.GenerateCodeFromCompileUnit(unit, stringWriter, genOptions);
                        break;
                    case Language.VisualBasic:
                        generator = new Microsoft.VisualBasic.VBCodeProvider().CreateGenerator();
                        generator.GenerateCodeFromCompileUnit(unit, stringWriter, null);
                        break;
                }

                return builder.ToString();
            }
        }
 protected RegexRouteConstraintBase(string pattern, RegexOptions options)
 {
     Pattern = pattern;
     // shouldn't these be included in the derrived classes by default: RegexOptions.CultureInvariant | RegexOptions.IgnoreCase?
     Options = options;  //no need to tell user that it is 'compiled' option...so do not include in public options
     CompiledExpression = new Regex(pattern, options | RegexOptions.Compiled);
 }
Example #22
0
 public RegEx(string pattern, string name, bool expectedMatch = true,
     RegexOptions options = RegexOptions.Compiled)
     : base(pattern, options)
 {
     Name = name;
     ExpectedMatch = expectedMatch;
 }
Example #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StringRules"/> class.
        /// </summary>
        /// <param name="minLength">The minimum string length allowed.</param>
        /// <param name="maxLength">The maximum string length allowed.</param>
        /// <param name="allowedChars">The set of allowed characters.</param>
        /// <param name="regexOptions">The additional regex options to use.</param>
        /// <param name="customerFilters">An optional collection of custom <see cref="Regex"/> patterns that describe
        /// additional restrictions.</param>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="minLength"/> is less than 0.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="maxLength"/> is less than
        /// <paramref name="minLength"/>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="minLength"/> is greater than
        /// <see cref="ushort.MaxValue"/>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="maxLength"/> is greater than
        /// <see cref="ushort.MaxValue"/>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="allowedChars"/> contains no defined groups.</exception>
        /// <exception cref="ArgumentException">At least one character group must be allowed.</exception>
        public StringRules(int minLength, int maxLength, CharType allowedChars, RegexOptions regexOptions = RegexOptions.None,
                           IEnumerable<Regex> customerFilters = null)
        {
            if (minLength < 0)
                throw new ArgumentOutOfRangeException("minLength");
            if (maxLength < minLength)
                throw new ArgumentOutOfRangeException("maxLength");
            if (minLength > ushort.MaxValue)
                throw new ArgumentOutOfRangeException("minLength");
            if (maxLength > ushort.MaxValue)
                throw new ArgumentOutOfRangeException("maxLength");
            if ((int)allowedChars == 0)
                throw new ArgumentException("At least one character group must be allowed.", "allowedChars");

            _minLength = (ushort)minLength;
            _maxLength = (ushort)maxLength;
            _allowedChars = allowedChars;

            var regexStr = BuildRegexString(minLength, maxLength, allowedChars);

            _regex = new Regex(regexStr, RegexOptions.Compiled | regexOptions);

            if (customerFilters != null)
                _customFilters = customerFilters.ToCompact();
        }
Example #24
0
 public Regex(string pattern, RegexOptions options)
 {
     this.refsInitialized = false;
     if (pattern == null)
     {
         throw new ArgumentNullException();
     }
     if ((options < RegexOptions.None) || ((((int) options) >> 9) != 0))
     {
         throw new ArgumentOutOfRangeException();
     }
     if (((options & RegexOptions.ECMAScript) != RegexOptions.None) && ((options & ~(RegexOptions.CultureInvariant | RegexOptions.ECMAScript | RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase)) != RegexOptions.None))
     {
         throw new ArgumentOutOfRangeException();
     }
     string text1 = options + ":" + pattern;
     this.pattern = pattern;
     this.roptions = options;
     RegexTree t = RegexParser.Parse(pattern, this.roptions);
     this.capnames = t._capnames;
     this.capslist = t._capslist;
     this.code = RegexWriter.Write(t);
     this.caps = this.code._caps;
     this.capsize = this.code._capsize;
 }
 public DynamicRegexArticleComparer(string comparator, RegexOptions options)
 {
     Comparator = comparator;
     Options = (options & ~RegexOptions.Compiled);
     // Create a regex to try it out. Throws an exception if there's a regex error
     new Regex(Tools.ApplyKeyWords("a", comparator), options);
 }
Example #26
0
		public GrepSink (IMiniStreamSink dest, string[] regexes, RegexOptions options) {
			this.dest = dest;

			this.regexes = new Regex[regexes.Length];
			for (int i = 0; i < regexes.Length; i++)
				this.regexes[i] = new Regex (regexes[i], options);
		}
 internal RegexNode(int type, RegexOptions options, int m, int n)
 {
     this._type = type;
     this._options = options;
     this._m = m;
     this._n = n;
 }
Example #28
0
		public RegexTrial (string pattern, RegexOptions options, string input, string expected)
		{
			this.pattern = pattern;
			this.options = options;
			this.input = input;
			this.expected = expected;
		}
 internal Type FactoryTypeFromCode(RegexCode code, RegexOptions options, string typeprefix)
 {
     base._code = code;
     base._codes = code._codes;
     base._strings = code._strings;
     base._fcPrefix = code._fcPrefix;
     base._bmPrefix = code._bmPrefix;
     base._anchors = code._anchors;
     base._trackcount = code._trackcount;
     base._options = options;
     string str3 = Interlocked.Increment(ref _typeCount).ToString(CultureInfo.InvariantCulture);
     string typename = typeprefix + "Runner" + str3;
     string str2 = typeprefix + "Factory" + str3;
     this.DefineType(typename, false, typeof(RegexRunner));
     this.DefineMethod("Go", null);
     base.GenerateGo();
     this.BakeMethod();
     this.DefineMethod("FindFirstChar", typeof(bool));
     base.GenerateFindFirstChar();
     this.BakeMethod();
     this.DefineMethod("InitTrackCount", null);
     base.GenerateInitTrackCount();
     this.BakeMethod();
     Type newtype = this.BakeType();
     this.DefineType(str2, false, typeof(RegexRunnerFactory));
     this.DefineMethod("CreateInstance", typeof(RegexRunner));
     this.GenerateCreateInstance(newtype);
     this.BakeMethod();
     return this.BakeType();
 }
Example #30
0
 /// <summary>
 /// Проверка, что строка соответствует заданному шаблону
 /// </summary>
 /// <param name="testString">Проверяемая строка</param>
 /// <param name="template">Шаблон</param>
 /// <param name="options">Параметры сравнения</param>
 /// <param name="errorMessageFormatString">Текст ошибки</param>
 /// <param name="errorMessageArgs">Параметры для сообщения об ошибке</param>
 public static void IsMatch(string testString, string template, RegexOptions options, string errorMessageFormatString, params object[] errorMessageArgs)
 {
     if (testString == null || !Regex.IsMatch(testString, template, options))
     {
         Throw(errorMessageFormatString, errorMessageArgs);
     }
 }
Example #31
0
 public RegexNode(int type, RegexOptions options)
 {
     NType   = type;
     Options = options;
 }
        private static Match SearchContentRegularExpression(string text, string searchString, RegexOptions regexOptions, out Regex regex)
        {
            try
            {
                regex = new Regex(searchString, regexOptions);
                return(regex.Match(text));
            }
            catch
            {
                // catch all; ignore
            }

            regex = null;
            return(null);
        }
Example #33
0
 /// <summary>
 /// Indicates that the search string(s) should be treated as a regular expression(s)
 /// with the specified options.
 /// </summary>
 /// <param name="regexOptions">The options to use (if any).</param>
 /// <returns>The current module instance.</returns>
 public Replace IsRegex(RegexOptions regexOptions = RegexOptions.None)
 {
     _isRegex      = true;
     _regexOptions = regexOptions;
     return(this);
 }
Example #34
0
        public static void IsMatch([InvokerParameterName] string paramName, string paramValue, string pattern, RegexOptions regexOptions = RegexOptions.None)
        {
            IsNotNull(nameof(paramValue), paramValue);
            IsNotNull(nameof(pattern), pattern);

            if (Regex.IsMatch(paramValue, pattern, regexOptions))
            {
                return;
            }

            var error = $"Argument '{paramName}' doesn't match with pattern '{pattern}'";

            //Log.Error(error);
            throw new ArgumentException(error, paramName);
        }
Example #35
0
        private static IEnumerable <string> GetTextByRegexPattern(this string text, string pattern, RegexOptions regexOptions = RegexOptions.None, bool IsCapitalizedOnly = true)
        {
            var results = new HashSet <string>();

            if (string.IsNullOrEmpty(text))
            {
                return(results);
            }

            var matches = Regex.Matches(text, pattern, regexOptions).Cast <Match>();

            foreach (var match in matches)
            {
                foreach (var group in match.Groups.Cast <Group>().Skip(1))
                {
                    var matchedText = group.Value.RemoveNonWordCharacters();

                    if (string.IsNullOrEmpty(matchedText) ||
                        (IsCapitalizedOnly && !matchedText.IsCapitalized()))
                    {
                        continue;
                    }

                    results.Add(matchedText);
                }
            }

            return(results);
        }
Example #36
0
        public void open()
        {
            FileStream      ts = new FileStream(m_path, FileMode.Open, FileAccess.Read, FileShare.None);
            string          ln = null;
            recFakturastr_k rec;
            RegexOptions    options         = ((RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline) | RegexOptions.IgnoreCase);
            Regex           regexFaknr      = new Regex("(^[0-9]*)=(.*$)", options);
            Regex           regexFakturastr = new Regex("(?:^|,)(\\\"(?:[^\\\"]+|\\\"\\\")*\\\"|[^,]*)", options);

            using (StreamReader sr = new StreamReader(ts, Encoding.Default))
            {
                while ((ln = sr.ReadLine()) != null)
                {
                    MatchCollection collFaknr = regexFaknr.Matches(ln);
                    string[]        value1    = new string[2];

                    foreach (Match m in collFaknr)
                    {
                        for (int j = 1; j <= 2; j++)
                        {
                            if (m.Groups[j].Success)
                            {
                                value1[j - 1] = m.Groups[j].ToString().Trim();
                            }
                        }
                    }
                    int    wFakid = int.Parse(value1[0]);
                    string ln2    = value1[1];

                    MatchCollection collFakturastr = regexFakturastr.Matches(ln2);
                    int             i     = 0;
                    int             iMax  = collFakturastr.Count;
                    string[]        value = new string[iMax];
                    foreach (Match m in collFakturastr)
                    {
                        for (int j = 1; j <= 3; j++)
                        {
                            if (m.Groups[j].Success)
                            {
                                if (i < iMax)
                                {
                                    value[i++] = m.Groups[j].ToString().Trim();
                                    break;
                                }
                            }
                        }
                    }


                    rec = new recFakturastr_k
                    {
                        Fakid = wFakid,
                        //FakNavnAdresse = value[0],
                        LevNavnAdresse = value[1],
                        Note           = value[2],
                        Felt03         = value[3],
                        Felt04         = value[4],
                        Felt05         = value[5],
                        Felt06         = value[6],
                        Felt07         = value[7],
                        Felt08         = value[8],
                        DeresRef       = value[9],
                        Felt10         = value[10],
                        Cvrnr          = value[11],
                        Felt12         = value[12],
                    };
                    this.Add(rec);
                }
            }
        }
Example #37
0
 public AndConstraint <CommandResultAssertions> HaveStdErrMatching(string pattern, RegexOptions options = RegexOptions.None)
 {
     Execute.Assertion.ForCondition(Regex.IsMatch(Result.StdErr, pattern, options))
     .FailWithPreformatted($"Matching the command error output failed. Pattern: '{pattern}'{GetDiagnosticsInfo()}");
     return(new AndConstraint <CommandResultAssertions>(this));
 }
Example #38
0
        static CellFormatPart()
        {
            NAMED_COLORS = new Dictionary <String, Color>(CASE_INSENSITIVE_ORDER);

            Hashtable colors = HSSFColor.GetIndexHash();

            foreach (object v in colors.Values)
            {
                HSSFColor hc   = (HSSFColor)v;
                Type      type = hc.GetType();
                String    name = type.Name;
                if (name.Equals(name.ToUpper()))
                {
                    byte[] rgb = hc.RGB;
                    Color  c   = Color.FromArgb(rgb[0], rgb[1], rgb[2]);
                    if (!NAMED_COLORS.ContainsKey(name))
                    {
                        NAMED_COLORS.Add(name, c);
                    }
                    if (name.IndexOf('_') > 0)
                    {
                        if (!NAMED_COLORS.ContainsKey(name.Replace('_', ' ')))
                        {
                            NAMED_COLORS.Add(name.Replace('_', ' '), c);
                        }
                    }
                    if (name.IndexOf("_PERCENT") > 0)
                    {
                        if (!NAMED_COLORS.ContainsKey(name.Replace("_PERCENT", "%").Replace('_', ' ')))
                        {
                            NAMED_COLORS.Add(name.Replace("_PERCENT", "%").Replace('_', ' '), c);
                        }
                    }
                }
            }
            // A condition specification
            String condition = "([<>=]=?|!=|<>)    # The operator\n" +
                               "  \\s*([0-9]+(?:\\.[0-9]*)?)\\s*  # The constant to test against\n";

            String color =
                "\\[(black|blue|cyan|green|magenta|red|white|yellow|color [0-9]+)\\]";

            // A number specification
            // Note: careful that in something like ##, that the trailing comma is not caught up in the integer part

            // A part of a specification
            String part = "\\\\.                 # Quoted single character\n" +
                          "|\"([^\\\\\"]|\\\\.)*\"         # Quoted string of characters (handles escaped quotes like \\\") \n" +
                          "|_.                             # Space as wide as a given character\n" +
                          "|\\*.                           # Repeating fill character\n" +
                          "|@                              # Text: cell text\n" +
                          "|([0?\\#](?:[0?\\#,]*))         # Number: digit + other digits and commas\n" +
                          "|e[-+]                          # Number: Scientific: Exponent\n" +
                          "|m{1,5}                         # Date: month or minute spec\n" +
                          "|d{1,4}                         # Date: day/date spec\n" +
                          "|y{2,4}                         # Date: year spec\n" +
                          "|h{1,2}                         # Date: hour spec\n" +
                          "|s{1,2}                         # Date: second spec\n" +
                          "|am?/pm?                        # Date: am/pm spec\n" +
                          "|\\[h{1,2}\\]                   # Elapsed time: hour spec\n" +
                          "|\\[m{1,2}\\]                   # Elapsed time: minute spec\n" +
                          "|\\[s{1,2}\\]                   # Elapsed time: second spec\n" +
                          "|[^;]                           # A character\n" + "";

            String format = "(?:" + color + ")?                  # Text color\n" +
                            "(?:\\[" + condition + "\\])?                # Condition\n" +
                            "((?:" + part + ")+)                        # Format spec\n";

            RegexOptions flags = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled;

            COLOR_PAT         = new Regex(color, flags);
            CONDITION_PAT     = new Regex(condition, flags);
            SPECIFICATION_PAT = new Regex(part, flags);
            FORMAT_PAT        = new Regex(format, flags);

            // Calculate the group numbers of important groups.  (They shift around
            // when the pattern is Changed; this way we figure out the numbers by
            // experimentation.)

            COLOR_GROUP = FindGroup(FORMAT_PAT, "[Blue]@", "Blue");
            CONDITION_OPERATOR_GROUP = FindGroup(FORMAT_PAT, "[>=1]@", ">=");
            CONDITION_VALUE_GROUP    = FindGroup(FORMAT_PAT, "[>=1]@", "1");
            SPECIFICATION_GROUP      = FindGroup(FORMAT_PAT, "[Blue][>1]\\a ?", "\\a ?");
        }
        public static IRuleBuilder <T, string> Matches <T>(this IRuleBuilder <T, string> builder, string expression, RegexOptions options)
        {
            builder.CheckNull(nameof(builder));
            expression.CheckNull(nameof(expression));

            builder.AddValidator(new MatchesValidator(builder.Rule.Property.Name, expression, options));

            return(builder);
        }
Example #40
0
        public void Read(string fname)
        {
            string input = File.ReadAllText(fname);

            RegexOptions options = RegexOptions.None;
            Regex        regex   = new Regex("[ ]{2,}", options);

            input = regex.Replace(input, " ");

            string[] lines = input.Split('\n');

            Vector3   v;
            OBJObject o = null;
            OBJGroup  g = null;

            for (int i = 0; i < lines.Length; i++)
            {
                string[] args = lines[i].Split(' ');
                switch (args[0])
                {
                case "v":
                    if (o == null)
                    {
                        o = new OBJObject();
                        g = new OBJGroup();
                        o.groups.Add(g);
                        objects.Add(o);
                    }
                    v = new Vector3(float.Parse(args[1]), float.Parse(args[2]), float.Parse(args[3]));
                    this.v.Add(v);
                    break;

                case "vn":
                    v = new Vector3(float.Parse(args[1]), float.Parse(args[2]), float.Parse(args[3]));
                    vn.Add(v);
                    break;

                case "vt":
                    vt.Add(new Vector2(float.Parse(args[1]), float.Parse(args[2])));
                    break;

                case "f":
                    g.v.Add(int.Parse(args[1].Split('/')[0]) - 1);
                    g.v.Add(int.Parse(args[2].Split('/')[0]) - 1);
                    g.v.Add(int.Parse(args[3].Split('/')[0]) - 1);
                    if (args[1].Split('/').Length > 1)
                    {
                        g.vt.Add(int.Parse(args[1].Split('/')[2]) - 1);
                        g.vt.Add(int.Parse(args[2].Split('/')[2]) - 1);
                        g.vt.Add(int.Parse(args[3].Split('/')[2]) - 1);
                    }
                    if (args[1].Split('/').Length > 2)
                    {
                        g.vn.Add(int.Parse(args[1].Split('/')[1]) - 1);
                        g.vn.Add(int.Parse(args[2].Split('/')[1]) - 1);
                        g.vn.Add(int.Parse(args[3].Split('/')[1]) - 1);
                    }
                    break;

                case "o":
                    o      = new OBJObject();
                    o.name = args[1];
                    objects.Add(o);
                    g = new OBJGroup();
                    o.groups.Add(g);
                    break;

                case "g":
                    g = new OBJGroup();
                    if (o == null || args.Length > 1)
                    {
                        o = new OBJObject();
                        if (args.Length > 1)
                        {
                            o.name = args[1];
                        }
                        objects.Add(o);
                    }
                    o.groups.Add(g);
                    break;
                }
            }
        }
Example #41
0
 /// <summary>
 ///     Enforces that a <see cref="string" /> value matches a specified regular expression pattern.
 /// </summary>
 /// <param name="value">The value to be checked.</param>
 /// <param name="regularExpression">The regular expression used for evaluation of the value.</param>
 /// <param name="propertyName">
 ///     The name of the property where the field is being set.
 ///     If the <paramref name="propertyName" /> is <c>null</c> the property name is automatically used.
 /// </param>
 /// <param name="regexOptions">Provides enumerated values to use to set regular expression options.</param>
 /// <returns>The value that has been successfully checked.</returns>
 /// <exception cref="System.ArgumentNullException"><paramref name="value" /> is <c>null</c>.</exception>
 /// ///
 /// <exception cref="System.ArgumentNullException"><paramref name="regularExpression" /> is <c>null</c>.</exception>
 /// <exception cref="System.ArgumentException">
 ///     <paramref name="value" /> does not match the
 ///     <paramref name="regularExpression" /> pattern.
 /// </exception>
 public static string Regex(string value, string regularExpression,
                            [CallerMemberName] string propertyName = "",
                            RegexOptions regexOptions = RegexOptions.None)
 {
     return(Check.Regex(value, regularExpression, propertyName, regexOptions));
 }
 /// <summary>
 /// 是否匹配
 /// </summary>
 /// <param name="self"></param>
 /// <param name="pattern"></param>
 /// <param name="options"></param>
 /// <returns></returns>
 public static bool IsMatch(this string self, string pattern, RegexOptions options)
 {
     return(!string.IsNullOrEmpty(self) && Regex.IsMatch(self, pattern, options));
 }
Example #43
0
        /// <summary>
        /// Combine adjacent sets/chars.
        /// Basic optimization. Single-letter alternations can be replaced
        /// by faster set specifications, and nested alternations with no
        /// intervening operators can be flattened:
        ///
        /// a|b|c|def|g|h -> [a-c]|def|[gh]
        /// apple|(?:orange|pear)|grape -> apple|orange|pear|grape
        /// </summary>
        private RegexNode ReduceAlternation()
        {
            if (Children == null)
            {
                return(new RegexNode(Nothing, Options));
            }

            bool         wasLastSet          = false;
            bool         lastNodeCannotMerge = false;
            RegexOptions optionsLast         = 0;
            RegexOptions optionsAt;
            int          i;
            int          j;
            RegexNode    at;
            RegexNode    prev;

            for (i = 0, j = 0; i < Children.Count; i++, j++)
            {
                at = Children[i];

                if (j < i)
                {
                    Children[j] = at;
                }

                for (; ;)
                {
                    if (at.NType == Alternate)
                    {
                        for (int k = 0; k < at.Children.Count; k++)
                        {
                            at.Children[k].Next = this;
                        }

                        Children.InsertRange(i + 1, at.Children);
                        j--;
                    }
                    else if (at.NType == Set || at.NType == One)
                    {
                        // Cannot merge sets if L or I options differ, or if either are negated.
                        optionsAt = at.Options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase);


                        if (at.NType == Set)
                        {
                            if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge || !RegexCharClass.IsMergeable(at.Str))
                            {
                                wasLastSet          = true;
                                lastNodeCannotMerge = !RegexCharClass.IsMergeable(at.Str);
                                optionsLast         = optionsAt;
                                break;
                            }
                        }
                        else if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge)
                        {
                            wasLastSet          = true;
                            lastNodeCannotMerge = false;
                            optionsLast         = optionsAt;
                            break;
                        }


                        // The last node was a Set or a One, we're a Set or One and our options are the same.
                        // Merge the two nodes.
                        j--;
                        prev = Children[j];

                        RegexCharClass prevCharClass;
                        if (prev.NType == One)
                        {
                            prevCharClass = new RegexCharClass();
                            prevCharClass.AddChar(prev.Ch);
                        }
                        else
                        {
                            prevCharClass = RegexCharClass.Parse(prev.Str);
                        }

                        if (at.NType == One)
                        {
                            prevCharClass.AddChar(at.Ch);
                        }
                        else
                        {
                            RegexCharClass atCharClass = RegexCharClass.Parse(at.Str);
                            prevCharClass.AddCharClass(atCharClass);
                        }

                        prev.NType = Set;
                        prev.Str   = prevCharClass.ToStringClass();
                    }
                    else if (at.NType == Nothing)
                    {
                        j--;
                    }
                    else
                    {
                        wasLastSet          = false;
                        lastNodeCannotMerge = false;
                    }
                    break;
                }
            }

            if (j < i)
            {
                Children.RemoveRange(j, i - j);
            }

            return(StripEnation(Nothing));
        }
Example #44
0
        /// <summary>
        /// Eliminate empties and concat adjacent strings/chars.
        /// Basic optimization. Adjacent strings can be concatenated.
        ///
        /// (?:abc)(?:def) -> abcdef
        /// </summary>
        private RegexNode ReduceConcatenation()
        {
            if (Children == null)
            {
                return(new RegexNode(Empty, Options));
            }

            bool         wasLastString = false;
            RegexOptions optionsLast   = 0;
            RegexOptions optionsAt;
            int          i;
            int          j;

            for (i = 0, j = 0; i < Children.Count; i++, j++)
            {
                RegexNode at;
                RegexNode prev;

                at = Children[i];

                if (j < i)
                {
                    Children[j] = at;
                }

                if (at.NType == Concatenate &&
                    ((at.Options & RegexOptions.RightToLeft) == (Options & RegexOptions.RightToLeft)))
                {
                    for (int k = 0; k < at.Children.Count; k++)
                    {
                        at.Children[k].Next = this;
                    }

                    Children.InsertRange(i + 1, at.Children);
                    j--;
                }
                else if (at.NType == Multi ||
                         at.NType == One)
                {
                    // Cannot merge strings if L or I options differ
                    optionsAt = at.Options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase);

                    if (!wasLastString || optionsLast != optionsAt)
                    {
                        wasLastString = true;
                        optionsLast   = optionsAt;
                        continue;
                    }

                    prev = Children[--j];

                    if (prev.NType == One)
                    {
                        prev.NType = Multi;
                        prev.Str   = Convert.ToString(prev.Ch, CultureInfo.InvariantCulture);
                    }

                    if ((optionsAt & RegexOptions.RightToLeft) == 0)
                    {
                        if (at.NType == One)
                        {
                            prev.Str += at.Ch.ToString();
                        }
                        else
                        {
                            prev.Str += at.Str;
                        }
                    }
                    else
                    {
                        if (at.NType == One)
                        {
                            prev.Str = at.Ch.ToString() + prev.Str;
                        }
                        else
                        {
                            prev.Str = at.Str + prev.Str;
                        }
                    }
                }
                else if (at.NType == Empty)
                {
                    j--;
                }
                else
                {
                    wasLastString = false;
                }
            }

            if (j < i)
            {
                Children.RemoveRange(j, i - j);
            }

            return(StripEnation(Empty));
        }
Example #45
0
 public RegexNode(int type, RegexOptions options, string str)
 {
     NType   = type;
     Options = options;
     Str     = str;
 }
Example #46
0
 public RegexNode(int type, RegexOptions options, int m)
 {
     NType   = type;
     Options = options;
     M       = m;
 }
Example #47
0
 public static Match Match(this string value, string pattern, RegexOptions options = RegexOptions.IgnoreCase)
 {
     return(Regex.Match(value, pattern, options));
 }
Example #48
0
 public RegexNode(int type, RegexOptions options, char ch)
 {
     NType   = type;
     Options = options;
     Ch      = ch;
 }
Example #49
0
 /// <summary>
 /// In a specified input string, replaces all substrings that match a specified regular expression with a string returned by a System.Text.RegularExpressions.MatchEvaluator delegate. Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.
 /// </summary>
 /// <param name="input">The string to search for a match.</param>
 /// <param name="pattern">The regular expression pattern to match.</param>
 /// <param name="evaluator">A custom method that examines each match and returns either the original matched string or a replacement string.</param>
 /// <param name="options">A bitwise combination of enumeration values that provide options for matching.</param>
 /// <param name="matchTimeout">A time-out interval, or System.Text.RegularExpressions.Regex.InfiniteMatchTimeout to indicate that the method should not time out.</param>
 /// <returns>A new string that is identical to the input string, except that the replacement string takes the place of each matched string. If pattern is not matched in the current instance, the method returns the current instance unchanged.</returns>
 /// <exception cref="System.ArgumentException">A regular expression parsing error occurred.</exception>
 /// <exception cref="System.ArgumentNullException">input, pattern, or evaluator is null.</exception>
 /// <exception cref="System.ArgumentOutOfRangeException">options is not a valid bitwise combination of System.Text.RegularExpressions.RegexOptions values.-or-matchTimeout is negative, zero, or greater than approximately 24 days.</exception>
 /// <exception cref="System.Text.RegularExpressions.RegexMatchTimeoutException">A time-out occurred. For more information about time-outs, see the Remarks section.</exception>
 public static string ReplacePattern(this string input, string pattern, MatchEvaluator evaluator, RegexOptions options, TimeSpan matchTimeout) => Regex.Replace(input, pattern, evaluator, options, matchTimeout);
Example #50
0
 public RegexHandle(string regexPattern, string helpText, RegexOptions regexOptions = RegexOptions.IgnoreCase)
 {
     _regex         = new Regex(regexPattern ?? string.Empty, regexOptions);
     HandleHelpText = helpText ?? string.Empty;
 }
        public void NotIsMatch_ValidInput_DoesNotThrowException(string input, string pattern, RegexOptions options = RegexOptions.None)
        {
            Exception exception = new Exception();

            Should.NotThrow(() => Guard.NotIsMatch(input, pattern, exception, options));
        }
Example #52
0
 public RegexHandle(string regexPattern, RegexOptions regexOptions = RegexOptions.IgnoreCase)
     : this(regexPattern, regexPattern, regexOptions)
 {
 }
Example #53
0
 /// <summary>
 /// Indicates whether the specified regular expression finds a match in the specified input string, using the specified matching options and time-out interval.
 /// </summary>
 /// <param name="input">The string to search for a match.</param>
 /// <param name="pattern">The regular expression pattern to match.</param>
 /// <param name="options">A bitwise combination of the enumeration values that provide options for matching.</param>
 /// <param name="matchTimeout">A time-out interval, or System.Text.RegularExpressions.Regex.InfiniteMatchTimeout to indicate that the method should not time out.</param>
 /// <returns>true if the regular expression finds a match; otherwise, false.</returns>
 /// <exception cref="System.ArgumentException">A regular expression parsing error occurred.</exception>
 /// <exception cref="System.ArgumentNullException">input or pattern is null.</exception>
 /// <exception cref="System.ArgumentOutOfRangeException">options is not a valid System.Text.RegularExpressions.RegexOptions value.-or-matchTimeout is negative, zero, or greater than approximately 24 days.</exception>
 /// <exception cref="System.Text.RegularExpressions.RegexMatchTimeoutException">A time-out occurred. For more information about time-outs, see the Remarks section.</exception>
 public static bool IsMatch(this string input, string pattern, RegexOptions options, TimeSpan matchTimeout) => Regex.IsMatch(input, pattern, options, matchTimeout);
        private string PerformFindAndReplace(string Find, string Replace, string ArticleText, string ArticleTitle, RegexOptions ROptions)
        {
            Find    = Tools.ApplyKeyWords(ArticleTitle, Find);
            Replace = Tools.ApplyKeyWords(ArticleTitle, PrepareReplacePart(Replace));

            findRegex = new Regex(Find, ROptions);
            Matches   = findRegex.Matches(ArticleText);

            if (Matches.Count > 0)
            {
                ArticleText = findRegex.Replace(ArticleText, Replace);

                if (Matches[0].Value != Matches[0].Result(Replace))
                {
                    summary = Matches[0].Value + Arrow + Matches[0].Result(Replace);

                    if (Matches.Count > 1)
                    {
                        summary += " (" + Matches.Count.ToString() + ")";
                    }

                    streditsummary += summary + ", ";
                }
            }

            return(ArticleText);
        }
Example #55
0
 /// <summary>
 /// Splits an input string into an array of substrings at the positions defined by a specified regular expression pattern. Specified options modify the matching operation.
 /// </summary>
 /// <param name="input">The string to split.</param>
 /// <param name="pattern">The regular expression pattern to match.</param>
 /// <param name="options">A bitwise combination of the enumeration values that provide options for matching.</param>
 /// <returns>An array of strings.</returns>
 /// <exception cref="System.ArgumentException">A regular expression parsing error occurred.</exception>
 /// <exception cref="System.ArgumentNullException">input or pattern is null.</exception>
 /// <exception cref="System.ArgumentOutOfRangeException">options is not a valid bitwise combination of System.Text.RegularExpressions.RegexOptions values.</exception>
 /// <exception cref="System.Text.RegularExpressions.RegexMatchTimeoutException">A time-out occurred. For more information about time-outs, see the Remarks section.</exception>
 public static string[] Split(this string input, string pattern, RegexOptions options) => Regex.Split(input, pattern, options);
Example #56
0
 /// <summary>
 /// Searches the input string for the first occurrence of the specified regular expression, using the specified matching options.
 /// </summary>
 /// <param name="input">The string to search for a match.</param>
 /// <param name="pattern">The regular expression pattern to match.</param>
 /// <param name="options">A bitwise combination of the enumeration values that provide options for matching.</param>
 /// <returns>An object that contains information about the match.</returns>
 /// <exception cref="System.ArgumentException">A regular expression parsing error occurred.</exception>
 /// <exception cref="System.ArgumentNullException">input or pattern is null.</exception>
 /// <exception cref="System.ArgumentOutOfRangeException">options is not a valid bitwise combination of System.Text.RegularExpressions.RegexOptions values.</exception>
 /// <exception cref="System.Text.RegularExpressions.RegexMatchTimeoutException">A time-out occurred. For more information about time-outs, see the Remarks section.</exception>
 public static Match Match(this string input, string pattern, RegexOptions options) => Regex.Match(input, pattern, options);
Example #57
0
 /// <summary>
 /// In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. Specified options modify the matching operation.
 /// </summary>
 /// <param name="input">The string to search for a match.</param>
 /// <param name="pattern">The regular expression pattern to match.</param>
 /// <param name="replacement">The replacement string.</param>
 /// <param name="options">A bitwise combination of the enumeration values that provide options for matching.</param>
 /// <returns>A new string that is identical to the input string, except that the replacement string takes the place of each matched string. If pattern is not matched in the current instance, the method returns the current instance unchanged.</returns>
 /// <exception cref="System.ArgumentException">A regular expression parsing error occurred.</exception>
 /// <exception cref="System.ArgumentNullException">input, pattern, or replacement is null.</exception>
 /// <exception cref="System.ArgumentOutOfRangeException">options is not a valid bitwise combination of System.Text.RegularExpressions.RegexOptions values.</exception>
 /// <exception cref="System.Text.RegularExpressions.RegexMatchTimeoutException">A time-out occurred. For more information about time-outs, see the Remarks section.</exception>
 public static string ReplacePattern(this string input, string pattern, string replacement, RegexOptions options) => Regex.Replace(input, pattern, replacement, options);
Example #58
0
 /// <summary>
 /// Splits an input string into an array of substrings at the positions defined by a specified regular expression pattern. Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.
 /// </summary>
 /// <param name="input">The string to split.</param>
 /// <param name="pattern">The regular expression pattern to match.</param>
 /// <param name="options">A bitwise combination of the enumeration values that provide options for matching.</param>
 /// <param name="matchTimeout">A time-out interval, or System.Text.RegularExpressions.Regex.InfiniteMatchTimeout to indicate that the method should not time out.</param>
 /// <returns>A string array.</returns>
 /// <exception cref="System.ArgumentException">A regular expression parsing error occurred.</exception>
 /// <exception cref="System.ArgumentNullException">input or pattern is null.</exception>
 /// <exception cref="System.ArgumentOutOfRangeException">options is not a valid bitwise combination of System.Text.RegularExpressions.RegexOptions values.-or-matchTimeout is negative, zero, or greater than approximately 24 days.</exception>
 /// <exception cref="System.Text.RegularExpressions.RegexMatchTimeoutException">A time-out occurred. For more information about time-outs, see the Remarks section.</exception>
 public static string[] Split(this string input, string pattern, RegexOptions options, TimeSpan matchTimeout) => Regex.Split(input, pattern, options, matchTimeout);
Example #59
0
 /// <summary>
 /// In a specified input string, replaces all strings that match a specified regular expression with a string returned by a System.Text.RegularExpressions.MatchEvaluator delegate. Specified options modify the matching operation.
 /// </summary>
 /// <param name="input">The string to search for a match.</param>
 /// <param name="pattern">The regular expression pattern to match.</param>
 /// <param name="evaluator">A custom method that examines each match and returns either the original matched string or a replacement string.</param>
 /// <param name="options">A bitwise combination of the enumeration values that provide options for matching.</param>
 /// <returns>A new string that is identical to the input string, except that a replacement string takes the place of each matched string. If pattern is not matched in the current instance, the method returns the current instance unchanged.</returns>
 /// <exception cref="System.ArgumentException">A regular expression parsing error occurred.</exception>
 /// <exception cref="System.ArgumentNullException">input, pattern, or evaluator is null.</exception>
 /// <exception cref="System.ArgumentOutOfRangeException">options is not a valid bitwise combination of System.Text.RegularExpressions.RegexOptions values.</exception>
 /// <exception cref="System.Text.RegularExpressions.RegexMatchTimeoutException">A time-out occurred. For more information about time-outs, see the Remarks section.</exception>
 public static string ReplacePattern(this string input, string pattern, MatchEvaluator evaluator, RegexOptions options) => Regex.Replace(input, pattern, evaluator, options);
Example #60
0
 /// <summary>
 /// In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.
 /// </summary>
 /// <param name="input">The string to search for a match.</param>
 /// <param name="pattern">The regular expression pattern to match.</param>
 /// <param name="replacement">The replacement string.</param>
 /// <param name="options">A bitwise combination of the enumeration values that provide options for matching.</param>
 /// <param name="matchTimeout">A time-out interval, or System.Text.RegularExpressions.Regex.InfiniteMatchTimeout to indicate that the method should not time out.</param>
 /// <returns>A new string that is identical to the input string, except that the replacement string takes the place of each matched string. If pattern is not matched in the current instance, the method returns the current instance unchanged.</returns>
 /// <exception cref="System.ArgumentException">A regular expression parsing error occurred.</exception>
 /// <exception cref="System.ArgumentNullException">input, pattern, or replacement is null.</exception>
 /// <exception cref="System.ArgumentOutOfRangeException">options is not a valid bitwise combination of System.Text.RegularExpressions.RegexOptions values.-or-matchTimeout is negative, zero, or greater than approximately 24 days.</exception>
 /// <exception cref="System.Text.RegularExpressions.RegexMatchTimeoutException">A time-out occurred. For more information about time-outs, see the Remarks section.</exception>
 public static string ReplacePattern(this string input, string pattern, string replacement, RegexOptions options, TimeSpan matchTimeout) => Regex.Replace(input, pattern, replacement, options, matchTimeout);