GetGroupNames() public method

public GetGroupNames ( ) : string[]
return string[]
 internal RegExpMatch(ArrayPrototype parent, Regex regex, Match match, string input) : base(parent, typeof(RegExpMatch))
 {
     this.hydrated = false;
     this.regex = regex;
     this.matches = null;
     this.match = match;
     base.SetMemberValue("input", input);
     base.SetMemberValue("index", match.Index);
     base.SetMemberValue("lastIndex", (match.Length == 0) ? (match.Index + 1) : (match.Index + match.Length));
     string[] groupNames = regex.GetGroupNames();
     int num = 0;
     for (int i = 1; i < groupNames.Length; i++)
     {
         string name = groupNames[i];
         int num3 = regex.GroupNumberFromName(name);
         if (name.Equals(num3.ToString(CultureInfo.InvariantCulture)))
         {
             if (num3 > num)
             {
                 num = num3;
             }
         }
         else
         {
             Group group = match.Groups[name];
             base.SetMemberValue(name, group.Success ? group.ToString() : null);
         }
     }
     this.length = num + 1;
 }
Esempio n. 2
0
        /// <summary>
        /// Creates regular expression case
        /// </summary>
        /// <param name="regexPattern">Regular expression instance</param>
        /// <returns>Case expression</returns>
        public static Expression<Func<string, string>> Rx(Regex regexPattern)
        {
            var parameterExpression = Expression.Parameter(typeof (string), "strArg");
            var matchExpression = Expression.Variable(typeof (Match), "match");

            var retPoint = Expression.Label(typeof (string));
            var successProperty = Expression.Property(matchExpression, "Success");
            var resultProperty = Expression.Property(
                regexPattern.GetGroupNames().Length > 1 ?
                (Expression)Expression.Property(Expression.Property(matchExpression, "Groups"), "Item", Expression.Constant(1)) :
                matchExpression, "Value");

            var block = Expression.Block(new[] { matchExpression},
                Expression.Assign(matchExpression,
                    Expression.Call(
                        Expression.Constant(regexPattern, typeof(Regex)),
                        typeof (Regex).GetMethod("Match", new[] {typeof (string)}),
                        parameterExpression)),
                Expression.IfThenElse(
                    successProperty,
                    Expression.Return(retPoint, resultProperty),
                    Expression.Return(retPoint, Expression.Convert(Expression.Constant(null), typeof(string)))),
                Expression.Label(retPoint, Expression.Default(typeof(string)))
                );
            return Expression.Lambda<Func<string, string>>(block, parameterExpression);
        }
Esempio n. 3
0
 public static Dictionary<string, string> Parse(string input, string pattern)
 {
     var dict = new Dictionary<string, string>();
     try
     {
         var regex = new Regex(pattern, RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace);
         string[] names = regex.GetGroupNames();
         MatchCollection matches = regex.Matches(input);
         foreach (Match match in matches)
         {
             foreach (string name in names)
             {
                 if (dict.ContainsKey(name))
                 {
                     dict[name] += Environment.NewLine + match.Groups[name].Value;
                 }
                 else
                 {
                     dict.Add(name, match.Groups[name].Value);
                 }
             }
         }
     }
     catch (Exception e)
     {
     }
     return dict;
 }
Esempio n. 4
0
        /// <summary>
        /// Loads visual studio .sln solution
        /// </summary>
        /// <param name="solutionFileName"></param>
        /// <exception cref="System.IO.FileNotFoundException">The file specified in path was not found.</exception>
        public Solution(string solutionFileName)
        {
            _solutionFileName = solutionFileName;
            _slnLines = new List<object>();
            var slnTxt = File.ReadAllText(solutionFileName);
            //Match string like: Project("{66666666-7777-8888-9999-AAAAAAAAAAAA}") = "ProjectName", "projectpath.csproj", "{11111111-2222-3333-4444-555555555555}"
            var projMatcher = new Regex("Project\\(\"(?<ParentProjectGuid>{[A-F0-9-]+})\"\\) = \"(?<ProjectName>.*?)\", \"(?<RelativePath>.*?)\", \"(?<ProjectGuid>{[A-F0-9-]+})");

            Regex.Replace(slnTxt, "^(.*?)[\n\r]*$", m =>
                    {
                        String line = m.Groups[1].Value;
                        Match m2 = projMatcher.Match(line);
                        if (m2.Groups.Count < 2)
                        {
                            _slnLines.Add(line);
                            return "";
                        }

                        var s = new SolutionProject();
                        // "0" - RegEx special kind of group
                        foreach (String g in projMatcher.GetGroupNames().Where(x => x != "0"))
                            s.GetType().GetField(g).SetValue(s, m2.Groups[g].ToString());

                        _slnLines.Add(s);
                        return "";
                    },
                    RegexOptions.Multiline);
        }
 internal ReplaceUsingFunction(Regex regex, ScriptFunction function, string source)
 {
     this.function = function;
     this.cArgs = function.GetNumberOfFormalParameters();
     bool flag = (function is Closure) && ((Closure) function).func.hasArgumentsObject;
     this.groupNumbers = null;
     this.source = source;
     if ((this.cArgs > 1) || flag)
     {
         string[] groupNames = regex.GetGroupNames();
         int num = groupNames.Length - 1;
         if (flag)
         {
             this.cArgs = num + 3;
         }
         if (num > 0)
         {
             if (num > (this.cArgs - 1))
             {
                 num = this.cArgs - 1;
             }
             this.groupNumbers = new int[num];
             for (int i = 0; i < num; i++)
             {
                 this.groupNumbers[i] = regex.GroupNumberFromName(groupNames[i + 1]);
             }
         }
     }
 }
Esempio n. 6
0
        public void Execute(string folder, int days, string dateFormat)
        {
            s_log.DebugFormat("Start Vaporizing Folders in {0}", folder);
            var dir = new DirectoryInfo(folder);

            foreach (var item in dir.GetDirectories())
            {
                Regex rgx = new Regex(dateFormat);
                Match m = rgx.Match(item.Name);
                if (m.Success)
                {
                    var groupNames = rgx.GetGroupNames();

                    int hour = groupNames.Contains("hour") ? Convert.ToInt32(m.Groups["hour"].Value) : 0;

                    DateTime d = new DateTime(Convert.ToInt32(m.Groups["year"].Value),
                                              Convert.ToInt32(m.Groups["month"].Value),
                                              Convert.ToInt32(m.Groups["day"].Value),
                                              hour, 0, 0);

                    if (d < DateTime.Now.AddDays(days * -1))
                    {
                        var name = item.FullName;
                        s_log.DebugFormat("Deleting folder {0}", name);
                        item.Delete(true);
                        s_log.DebugFormat("Finished Deleting folder {0}", name);
                    }

                }

                s_log.DebugFormat("Finished Vaporizing Folders in {0}", folder);
            }
        }
Esempio n. 7
0
		private void Navigate(string navigationState)
		{
			if (navigationState == currentUrl)
				return;
			currentUrl = navigationState;

			string database = Server.DefaultDatabaseName;
			var databasesMatch = databasesRegEx.Match(currentUrl);
			if (databasesMatch.Success)
			{
				currentUrl = currentUrl.Substring(databasesMatch.Length);
				database = databasesMatch.Groups[1].Value;
			}

			foreach (var route in Routes.OrderBy(x => x.Metadata.Index))
			{
				var regex = new Regex(route.Metadata.Url);
				var match = regex.Match(navigationState);
				if (match.Success == false)
					continue;

				var parameters = new Dictionary<string, string>();
				foreach (var name in regex.GetGroupNames())
				{
					parameters[name] = match.Groups[name].Value;
				}
				route.Value.Navigate(database, parameters);
				return;
			}
		}
Esempio n. 8
0
        public static bool Handle(string path)
        {
            var viewDispatcher = Mvx.Resolve<Cirrious.MvvmCross.Views.IMvxViewDispatcher>();
            var appService = Mvx.Resolve<IApplicationService>();
            if (!path.EndsWith("/", StringComparison.Ordinal))
                path += "/";

            foreach (var route in Routes)
            {
                var regex = new Regex(route.Path, RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
                var match = regex.Match(path);
                var groups = regex.GetGroupNames().Skip(1);

                if (match.Success)
                {
                    var rec = new MvxViewModelRequest();
                    rec.ViewModelType = route.ViewModelType;
                    rec.ParameterValues = new Dictionary<string, string>();
                    foreach (var group in groups)
                        rec.ParameterValues.Add(group, match.Groups[group].Value);
                    appService.SetUserActivationAction(() => viewDispatcher.ShowViewModel(rec));
                    return true;
                }
            }

            return false;
        }
Esempio n. 9
0
        private static void MatchAndPrintResults(Regex regex, string input)
        {
            Console.WriteLine("Regex: " + regex);
            Console.WriteLine("Input: " + input);

            MatchCollection matches = regex.Matches(input);
            Console.WriteLine("Match Count: " + matches.Count);

            int matchCounter = 0;
            foreach (Match match in matches)
            {
                Console.WriteLine(string.Empty.PadRight(50, '='));
                Console.WriteLine("  Match {0}:", ++matchCounter);
                Console.WriteLine("  Value: " + match.Value);

                Console.WriteLine(string.Empty.PadRight(50, '-'));
                Console.WriteLine("    Groups:");
                Console.WriteLine(string.Empty.PadRight(50, '-'));

                foreach (string name in regex.GetGroupNames())
                {
                    Console.WriteLine("    \"{0}\": {1}", name, match.Groups[name].Value);
                }
                Console.WriteLine(string.Empty.PadRight(50, '='));
            }

            Console.WriteLine();
        }
Esempio n. 10
0
        public static bool Handle(string path)
        {
            if (!path.EndsWith("/", StringComparison.Ordinal))
                path += "/";

            foreach (var route in Routes)
            {
                var regex = new Regex(route.Path, RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
                var match = regex.Match(path);
                var groups = regex.GetGroupNames().Skip(1).ToList();

                if (match.Success)
                {
                    var vm = IoC.Resolve(route.ViewModelType);
                    foreach (var group in groups)
                    {
                        var property = vm.GetType().GetProperty(group);
                        if (property != null)
                            property.SetValue(vm, match.Groups[group].Value);
                    }


                    //appService.SetUserActivationAction(() => viewDispatcher.ShowViewModel(rec));
                    return true;
                }
            }

            return false;
        }
Esempio n. 11
0
 /// <summary>
 /// Constructeur
 /// </summary>
 /// <param name="text">Texte à afficher</param>
 public Visionneuse(string text)
 {
     InitializeComponent();
     texte.Text = text;
     string integers = "\\b(?:[0-9]*\\.)?[0-9]+\\b";
     string Strings = "'[^']*";
     string all = "\\r|\\n|\\(|\\)|'[^']*'|\\w+|\\[max\\]|\\[min\\]|\\[avg\\]|\\[count\\]|\\|/|\\.|\\{|\\}|\\[|\\]|\\+|:-|:=|<>|[(<=)(>=)^?!,@<>_~%/=:;*'&-]{1}?|\\$|\\?}";
     string Comments = @"|/\*(?>(?:(?>[^*]+)|\*(?!/))*)\*/";// matches multiline comments
     string reg = "--|" + integers + "|" + Strings + "|" + all;
     Regex rg = new Regex(reg + Comments, RegexOptions.IgnoreCase);
     MatchCollection mc_ = rg.Matches(texte.Text);
     string[] a = rg.GetGroupNames();
     int j = 0;
     while (j < mc_.Count)
     {
         if (mc_[j].Value == "--")
         {
             while (mc_[j].Value != "\r")
             {
                 texte.SelectionStart = mc_[j].Index;
                 texte.SelectionLength = mc_[j].Length;
                 texte.SelectionFont = new Font("Courrier", 10, FontStyle.Italic);
                 texte.SelectionColor = CommentColor;
                 j++;
             }
         }
         ColorSQLToken(mc_[j]);
         j++;
     }
 }
 public bool ProcessRegex(string target, string regexExpression)
 {
     if (target == null)
     {
         target = string.Empty;
     }
     Regex regex = new Regex(regexExpression, RegexOptions.ExplicitCapture);
     Match match = regex.Match(target);
     if (!match.Success)
     {
         return false;
     }
     string[] groupNames = regex.GetGroupNames();
     if (groupNames.Length > 0)
     {
         if (this._groups == null)
         {
             this._groups = new Hashtable();
         }
         for (int i = 0; i < groupNames.Length; i++)
         {
             this._groups[groupNames[i]] = match.Groups[i].Value;
         }
     }
     return true;
 }
 public static IEnumerable Match(SqlString pattern, SqlString subject)
 {
     var list = new List<MatchContent>();
     var regex = new Regex(pattern.Value);
     var match = regex.Match(subject.Value);
     var groupNames = regex.GetGroupNames();
     var num = 0;
     while (match.Success)
     {
         num++;
         var array = groupNames;
         foreach (var text in array)
         {
             list.AddRange(match.Groups[text].Captures
                 .Cast<Capture>()
                 .Select(capture =>
                     new MatchContent
                     {
                         MatchNumber = num,
                         GroupName = text,
                         CaptureNumber = capture.Index,
                         Value = capture.Value
                     }));
         }
         match = match.NextMatch();
     }
     return list;
 }
Esempio n. 14
0
 public static string regexFun(string target, string expr, object g, regexAct ra, string replStr, int replCnt, int replStart, ref MatchCollection o, int capID) {
     int gn = g is int ? Int32.Parse(g.ToString()) : 0;
     if (capID < 0) { capID = 0; }
     Regex regex = new Regex(expr, RegexOptions.Multiline | RegexOptions.IgnoreCase);
     try {
         switch (ra) {
             case regexAct.Match:
                 var varMatch = regex.Match(target);
                 if (!varMatch.Success) {
                     return null;
                 } else if (g is String && Array.Exists(regex.GetGroupNames(), gpnm => (gpnm == g.ToString()))) {
                     return varMatch.Groups[g.ToString()].Captures[capID].Value;
                 } else if (g is int || Int32.TryParse(g.ToString(), out gn)) {
                     return varMatch.Groups[gn].Captures[capID].Value;
                 } else {
                     return varMatch.Groups[0].Captures[capID].Value;
                 }
             case regexAct.Replace:
                 return regex.Replace(target, (string)replStr, replCnt, replStart);
             case regexAct.Matches:
                 var ms = regex.Matches(target);
                 o = ms;
                 return "0";
             default:
                 return "err:-1";
         }
     } catch{
         return "err:-2";
     }
 }
Esempio n. 15
0
        public static int GetMatchStrength(string regexPattern, string input)
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(regexPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            if (!regex.IsMatch(input))
            {
                throw new Exception(string.Format("String '{0}' is not a match for Regex '{1}'", input, regexPattern));
            }

            // The idea is that you have a regex like
            //          look at (?<object>.*)
            // And you have a string like
            //          look at thing
            // The strength is the length of the "fixed" bit of the string, in this case "look at ".
            // So we calculate this as the length of the input string, minus the length of the
            // text that matches the named groups.

            int lengthOfTextMatchedByGroups = 0;

            foreach (string groupName in regex.GetGroupNames())
            {
                // exclude group names like "0", we only want the explicitly named groups
                if (!TextAdventures.Utility.Strings.IsNumeric(groupName))
                {
                    string groupMatch = regex.Match(input).Groups[groupName].Value;
                    lengthOfTextMatchedByGroups += groupMatch.Length;
                }
            }

            return(input.Length - lengthOfTextMatchedByGroups);
        }
Esempio n. 16
0
        /// <summary>
        /// 根据规则, 过滤出结果
        /// 
        /// </summary>
        /// <param name="rawContent"></param>
        /// <returns></returns>
        public override string FilterUsingRule(ref string rawContent)
        {
            string filteredContent = string.Empty;

            Regex reg = new Regex(RegexExp, RegexOptions.Singleline);
            string[] groupNames = reg.GetGroupNames();
            MatchCollection matchs = reg.Matches(rawContent);

            foreach (Match m in matchs)
            {
                //从原始内容中删除已经提取的内容
                if (m.Value == string.Empty) continue;
                rawContent = rawContent.Replace(m.Value, string.Empty);

                //继续提取精确内容,通过regexgroup

                for (int i = 0; i < m.Groups.Count; i++)
                {
                    string groupName = groupNames[i];
                    int demo;
                    if (!int.TryParse(groupName, out demo))
                    {
                        Group g = m.Groups[groupNames[i]];

                        filteredContent += g.Value + "||";
                    }
                }
                filteredContent += "&&";
            }

            return filteredContent;
        }
Esempio n. 17
0
        public RoutedRequest(IDictionary<string, object> env, Regex regex, string path)
            : base(env)
        {
            var groups = regex.Match(path).Groups;
            var dic = regex.GetGroupNames().ToDictionary(name => name, name => groups[name].Value);

            UrlSegments = new DynamicDictionary<string>(dic);
        }
Esempio n. 18
0
 static int GetGroupNames(IntPtr L)
 {
     LuaScriptMgr.CheckArgsCount(L, 1);
     System.Text.RegularExpressions.Regex obj = (System.Text.RegularExpressions.Regex)LuaScriptMgr.GetNetObjectSelf(L, 1, "System.Text.RegularExpressions.Regex");
     string[] o = obj.GetGroupNames();
     LuaScriptMgr.PushArray(L, o);
     return(1);
 }
Esempio n. 19
0
 public RouterContext(IOwinContext owinContext, Regex regex)
 {
     OwinContext = owinContext;
     var groupNames = regex.GetGroupNames();
     if (groupNames.Length > 1)
     {
         GetParams(owinContext, regex, groupNames.Skip(1));
     }
 }
Esempio n. 20
0
 private static void Debug(string input, Match match, Regex regex)
 {
     Trace.WriteLine("Regex: " + regex);
     Trace.WriteLine("Input: " + input);
     foreach(var groupName in regex.GetGroupNames())
     {
         Trace.WriteLine(" -> " + groupName + ": >>" + match.Groups[groupName].Value + "<<");
     }
 }
Esempio n. 21
0
        public SyslogParser(Regex parser)
        {
            if (parser == null)
            {
                throw new ArgumentNullException("parser");
            }

            this.parser = parser;
            this.groupNames = parser.GetGroupNames();
        }
Esempio n. 22
0
 private static string GetGitHubWikiAuthor(string html)
 {
     Regex rex = new Regex("class=\"author\">(.*?)</a> edited this page <time .*>(.*?)</time>");
     //var match = rex.Match(html);
     //return "Last edited by " + match.Groups["name"].Value + " on " + match.Groups["timeStamp"].Value;
     var match = rex.Match(html);
     string[] names = rex.GetGroupNames();
     string name = names.Length > 0 ? match.Groups[names[1]].Value : "unknown author";
     string time = names.Length > 1 ? match.Groups[names[2]].Value : "at unknown time";
     name = String.Format("<a href=\"http://github.com/{0}\">{0}</a>", name);
     return String.Format("Updated {1} by {0}", name, time);
 }
Esempio n. 23
0
 static public int GetGroupNames(IntPtr l)
 {
     try {
         System.Text.RegularExpressions.Regex self = (System.Text.RegularExpressions.Regex)checkSelf(l);
         var ret = self.GetGroupNames();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
        /// <summary>
        /// Constructs a new instance of <see cref="HttpStatusCodeParser"/> for the specified regular
        /// expression.
        /// </summary>
        /// <param name="pattern">
        /// The regular expression pattern to use.
        ///
        /// <para><paramref name="pattern"/> should contain the named capturing grounds <c>StatusCode</c> and <c>status</c>.</para>
        /// </param>
        /// <exception cref="ArgumentNullException"><paramref name="pattern"/> is <see langword="null"/>.</exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="pattern"/> does not contain a capturing group named <c>StatusCode</c>.
        /// <para>-or-</para>
        /// <para><paramref name="pattern"/> does not contain a capturing group named <c>Status</c>.</para>
        /// </exception>
        protected HttpStatusCodeParser(string pattern)
        {
            if (pattern == null)
                throw new ArgumentNullException("pattern");

            _expression = new Regex(pattern, RegexOptions.Compiled);

            string[] groupNames = _expression.GetGroupNames();
            if (!groupNames.Contains("StatusCode", StringComparer.Ordinal))
                throw new ArgumentException("The pattern does not contain a StatusCode named capturing group.", "pattern");
            if (!groupNames.Contains("Status", StringComparer.Ordinal))
                throw new ArgumentException("The pattern does not contain a Status named capturing group.", "pattern");
        }
        public static void NameTests()
        {
            string pattern = @"\b(?<FirstWord>\w+)\s?((\w+)\s)*(?<LastWord>\w+)?(?<Punctuation>\p{Po})";
            string input = "The cow jumped over the moon.";
            Regex regex = new Regex(pattern);
            Match match = regex.Match(input);
            Assert.True(match.Success);

            string[] names = regex.GetGroupNames();
            for (int i = 0; i < names.Length; i++)
            {
                Assert.Equal(names[i], match.Groups[i].Name);
            }
        }
Esempio n. 26
0
        public IBaseViewModel Handle(string url)
        {
            Uri uri;
            if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
                return null;

            if (_sessionService.Account == null)
                return null;

            Uri webDomain;
            if (!Uri.TryCreate(_sessionService.Account.WebDomain, UriKind.Absolute, out webDomain))
                return null;

            if (uri.Scheme != webDomain.Scheme || uri.Host != webDomain.Host)
                return null;

            var relativePath = string.Concat(uri.Segments);
            if (!relativePath.EndsWith("/", StringComparison.Ordinal))
                relativePath += "/";

            try
            {
                foreach (var route in Routes)
                {
                    var regex = new Regex(route.Path, RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase);
                    var match = regex.Match(relativePath);
                    var groups = regex.GetGroupNames().Skip(1).ToList();

                    if (match.Success)
                    {
//                        var vm = Locator.Current.GetService(route.ViewModelType);
////                        foreach (var group in groups)
////                        {
////                            var property = vm.GetType().GetProperty(group);
////                            if (property != null)
////                                property.SetValue(vm, match.Groups[group].Value);
////                        }
////
//                        return vm as IBaseViewModel;
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Unable to resolve Url (" + url + "): " + e.Message);
            }

            return null;
        }
Esempio n. 27
0
 public static void PrintAllCapturesToConsole(this Match match, Regex regex)
 {
     if (!match.Success)
     {
         Console.WriteLine("\t\tNo Match.");
         return;
     }
     var groupNames = regex.GetGroupNames();
     foreach (var groupName in groupNames)
     {
         var g = match.Groups[groupName];
         Console.WriteLine("\tGroup {0}",groupName);
         g.PrintCaptures();
     }
 }
Esempio n. 28
0
        public static RegMatches MatchGroups(string aInput, string aPattern)
        {
            RegMatches ret = new RegMatches();

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(aPattern);
            MatchCollection matchCollection            = regex.Matches(aInput);

            foreach (string groupName in regex.GetGroupNames())
            {
                if (groupName == "0")
                {
                    continue;
                }
                ret.Add(groupName, new List <string>());
            }

            bool isFound = false;

            if (matchCollection.Count != 0)
            {
                foreach (Match match in matchCollection)
                {
                    foreach (string groupName in ret.Keys)
                    {
                        foreach (Capture cap in match.Groups[groupName].Captures)
                        {
                            string val = cap.Value.Trim();
                            if (val == "")
                            {
                                continue;
                            }
                            ret[groupName].Add(cap.Value.Trim());
                            if (!isFound)
                            {
                                isFound = true;
                            }
                        }
                    }
                }
            }

            if (!isFound)
            {
                return(null);
            }
            return(ret);
        }
        public static string GroupValue(this string text, Regex regex)
        {
            var match = regex.Match(text);
            var names = regex.GetGroupNames();

            foreach (var name in names)
            {
                if (numericNames.Contains(name))
                    continue;
                int unused;
                if (int.TryParse(name, out unused))
                    continue;

                return match.Groups[name].Value;
            }
            return match.Groups[0].Value;
        }
Esempio n. 30
0
 public bool Retrieve(string content)
 {
     var regex = new Regex(Expression, RegexOptions.Multiline);
     var m = regex.Match(content);
     if (m.Success)
     {
         RetrivedData = new Dictionary<string, string>();
         foreach (var gName in regex.GetGroupNames())
         {
             RetrivedData[gName] = m.Groups[gName].Value;
         }
         return true;
     }
     else
     {
         return false;
     }
 }
Esempio n. 31
0
 internal ReplaceUsingFunction(Regex regex, ScriptFunction function, String source) {
   this.function = function;
   this.cArgs = function.GetNumberOfFormalParameters();
   bool hasArgumentsObject = (function is Closure) && ((Closure)function).func.hasArgumentsObject;
   this.groupNumbers = null;
   this.source = source;
   if (this.cArgs > 1 || hasArgumentsObject) {
     String[] groupNames = regex.GetGroupNames();
     int cGroupNumbers = groupNames.Length - 1;
     if (hasArgumentsObject) this.cArgs = cGroupNumbers+3;
     if (cGroupNumbers > 0) {
       if (cGroupNumbers > this.cArgs - 1)
         cGroupNumbers = this.cArgs - 1;
       this.groupNumbers = new int[cGroupNumbers];
       for (int i = 0; i < cGroupNumbers; i++)
         this.groupNumbers[i] = regex.GroupNumberFromName(groupNames[i+1]);
     }
   }
 }
Esempio n. 32
0
        public static RegMatche2[] Match(string aInput, string aPattern)
        {
            var ret        = new List <RegMatche2>();
            var groupNames = new List <string>();

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(aPattern);
            MatchCollection matchCollection            = regex.Matches(aInput);

            if (matchCollection.Count == 0)
            {
                return(null);
            }

            // Get group names
            foreach (string groupName in regex.GetGroupNames())
            {
                if (groupName == "0")
                {
                    continue;
                }
                groupNames.Add(groupName);
            }

            foreach (Match match in matchCollection)
            {
                foreach (var g in groupNames)
                {
                    var m = match.Groups[g];
                    if (m == null || m.Length == 0)
                    {
                        continue;
                    }
                    ret.Add(new RegMatche2()
                    {
                        GroupName = g,
                        Value     = match.Value
                    });
                }
            }

            return(ret.ToArray());
        }
Esempio n. 33
0
        public static RegexResult Evaluate(RegexQueryBuilder regexQuery)
        {
            RegexResult result = new RegexResult(regexQuery);

            Regex expression = new Regex(regexQuery.Regex, regexQuery.GetOptions());

            result.Regex = regexQuery.Regex;
            result.Replacement = regexQuery.ReplaceText;

            int searchPos = 0;

            List<string> groupNames = expression.GetGroupNames().ToList();
            Match m = expression.Match(regexQuery.Target, searchPos);

            SortedList sl = new SortedList();
            while (m.Success)
            {
                RegexMatch matchResult = new RegexMatch();
                groupNames.ForEach(groupName => {
                    var groupMatch = m.Groups[groupName];
                    foreach (Capture cap in groupMatch.Captures) {
                        RegexCaptureResult groupResult = new RegexCaptureResult()
                        {
                            Index = cap.Index,
                            MatchText = cap.Value,
                            MatchLength = cap.Length,
                            MatchGroupName = groupName
                        };
                        matchResult.GroupResults.Add(groupResult);
                    }
                });

                result.Matches.Add(matchResult);
                sl.Add(m.Index, m.Value);
                m = m.NextMatch();

            }

            result.MatchSortedList = sl;
            return result;
        }
Esempio n. 34
0
        public static QuestDictionary <string> Populate(string regexPattern, string input)
        {
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(regexPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            if (!regex.IsMatch(input))
            {
                throw new Exception(string.Format("String '{0}' is not a match for Regex '{1}'", input, regexPattern));
            }

            QuestDictionary <string> result = new QuestDictionary <string>();

            foreach (string groupName in regex.GetGroupNames())
            {
                if (!TextAdventures.Utility.Strings.IsNumeric(groupName))
                {
                    string groupMatch = regex.Match(input).Groups[groupName].Value;
                    result.Add(groupName, groupMatch);
                }
            }

            return(result);
        }
Esempio n. 35
0
        private void RegexTextBox_OnUserStopTyping(object sender, EventArgs e)
        {
            if (this.rtcRegexControl.RegexTextBox.Text.Length != 0)
            {
                TextChanged.RaiseEvent(this);
            }
            if (!this.rtcRegexControl.RegexTextBox.HasRegexError)
            {
                try
                {
                    Regex regex = new Regex(this.rtcRegexControl.RegexTextBox.Text);
                    EventArgs<List<string>> filesEvent = new EventArgs<List<string>>();
                    RequestFileList.RaiseEvent(this, filesEvent);

                    UpdateGroups(regex.GetGroupNames());
                }
                catch (Exception)
                {
                }
            }
        }
        public static NameValueCollection GetNamedMatches(Regex regex, Match m)
        {
            NameValueCollection dic = new NameValueCollection();

            foreach (string groupName in regex.GetGroupNames())
            {
                if (Regex.IsMatch(groupName, @"^\d"))
                    continue;

                var groupCapture = m.Groups[groupName];
                if (groupCapture.Success)
                {
                    foreach (Capture capture in groupCapture.Captures)
                    {
                        dic.Add(groupName, capture.Value);
                    }
                }
            }

            return dic;
        }
Esempio n. 37
0
 public string[] GetGroupNames()
 {
     return(_regex.GetGroupNames());
 }