public GroupNameFromNumber ( int i ) : string | ||
i | int | |
Résultat | string |
/// <summary> /// /// </summary> /// <param name="source"></param> /// <param name="matchPattern"></param> /// <param name="wantInitialMatch"></param> /// <returns></returns> public static ArrayList ExtractGroupings(string source, string matchPattern, bool wantInitialMatch) { ArrayList keyedMatches = new ArrayList(); int startingElement = 1; if (wantInitialMatch) { startingElement = 0; } Regex RE = new Regex(matchPattern, RegexOptions.Multiline); MatchCollection theMatches = RE.Matches(source); foreach (Match m in theMatches) { Hashtable groupings = new Hashtable(); for (int counter = startingElement; counter < m.Groups.Count; counter++) { // If we had just returned the MatchCollection directly, the // GroupNameFromNumber method would not be available to use groupings.Add(RE.GroupNameFromNumber(counter), m.Groups[counter]); } keyedMatches.Add(groupings); } return (keyedMatches); }
private void match() { treeView1.Nodes.Clear(); try { Regex r = new Regex(textBox2.Text); Match m = r.Match(textBox1.Text); while (m.Success) { TreeNode node = treeView1.Nodes.Add(m.Value); foreach (Group g in m.Groups) { node.Nodes.Add(r.GroupNameFromNumber(g.Index)).Nodes.Add(g.Value); } m = m.NextMatch(); } textBox3.Text = r.Replace(textBox1.Text, textBox4.Text); } catch (ArgumentException ex) { TreeNode node = treeView1.Nodes.Add(ex.Message); node.ForeColor = Color.Red; } }
public static IList<string> ExtractMentions(string message, IQueryable<ChatUserMention> mentions = null) { if (message == null) return new List<string>(); // Find username mentions var matches = Regex.Matches(message, UsernameMentionPattern) .Cast<Match>() .Where(m => m.Success) .Select(m => m.Groups["user"].Value.Trim()) .Where(u => !String.IsNullOrEmpty(u)) .ToList(); // Find custom mentions if (mentions == null || !mentions.Any()) return matches; var regex = new Regex(GetPattern(mentions), RegexOptions.IgnoreCase); foreach (var match in regex.Matches(message) .Cast<Match>() .Where(m => m.Success)) { for (var i = 1; i < match.Groups.Count; i++) { if (!match.Groups[i].Success) continue; matches.Add(regex.GroupNameFromNumber(i)); } } return matches; }
public static void ExtractGroups(this string text, Dictionary<string, string> groups, string regexPattern) { var regex = new Regex(regexPattern, RegexOptions.Multiline); var match = regex.Match(text); var index = 0; foreach (var group in match.Groups.OfType<Group>()) if (index++ > 0) groups.Add(regex.GroupNameFromNumber(index - 1), group.Value); }
static int GroupNameFromNumber(IntPtr L) { LuaScriptMgr.CheckArgsCount(L, 2); System.Text.RegularExpressions.Regex obj = (System.Text.RegularExpressions.Regex)LuaScriptMgr.GetNetObjectSelf(L, 1, "System.Text.RegularExpressions.Regex"); int arg0 = (int)LuaScriptMgr.GetNumber(L, 2); string o = obj.GroupNameFromNumber(arg0); LuaScriptMgr.Push(L, o); return(1); }
private static DynamicDictionary GetParameters(Regex regex, GroupCollection groups) { dynamic data = new DynamicDictionary(); for (var i = 1; i <= groups.Count; i++) { data[regex.GroupNameFromNumber(i)] = groups[i].Value; } return data; }
private static DynamicDictionary GetParameters(Regex regex, GroupCollection groups) { dynamic data = new DynamicDictionary(); for (int i = 1; i <= groups.Count; i++) { data[regex.GroupNameFromNumber(i)] = Uri.UnescapeDataString(groups[i].Value); } return data; }
static public int GroupNameFromNumber(IntPtr l) { try { System.Text.RegularExpressions.Regex self = (System.Text.RegularExpressions.Regex)checkSelf(l); System.Int32 a1; checkType(l, 2, out a1); var ret = self.GroupNameFromNumber(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
/// <summary> /// Initializes a new instance of the RegexMatch class. /// </summary> public RegexMatch(Match match, Regex regex) { int i = 0; foreach (Group g in match.Groups) { if (i != 0) { string groupName = regex.GroupNameFromNumber(i); _Groups.Add(new RegexGroup(g, groupName)); } i++; } this._Value = match.Value; this._Index = match.Index; this._Length = match.Length; }
public static ArrayList Match(SqlString inputText, SqlString pattern, bool isCaseSensitive) { ArrayList result = new ArrayList(); try { if (!inputText.IsNull && !string.IsNullOrEmpty(inputText.Value) && !pattern.IsNull && !string.IsNullOrEmpty(pattern.Value) ) { TextRegex regex = isCaseSensitive ? new TextRegex(pattern.Value) : new TextRegex(pattern.Value, RegexOptions.IgnoreCase); MatchCollection matches = regex.Matches(inputText.Value); for (int matchNumber = 0; matchNumber < matches.Count; ++matchNumber) { Match match = matches[matchNumber]; for (int groupNumber = 1; groupNumber < match.Groups.Count; ++groupNumber) { Group group = match.Groups[groupNumber]; string groupName = regex.GroupNameFromNumber(groupNumber); MatchGroupRow resultItem = new MatchGroupRow { GroupName = groupName, GroupNumber = groupNumber, Index = group.Index, Length = group.Length, MatchNumber = matchNumber, Value = group.Value }; result.Add(resultItem); } } } } catch { // ignored } return(result); }
public Dictionary<string, string> GetAddressParts(string path) { if (path == null) return null; if (_url == null) return null; var pattern = new Regex(_url); var match = pattern.Match(path); var addressParts = new Dictionary<string, string>(); var groupCollection = match.Groups; for (var i = 1; i <= groupCollection.Count; i++) { var key = pattern.GroupNameFromNumber(i); var value = groupCollection[i].Value; addressParts.Add(key, value); } return addressParts; }
// Public Methods public TreeNode[] Matches(string content, Regex regex) { MatchCollection matches = regex.Matches(content); List<TreeNode> nodesOfMatches = new List<TreeNode>(matches.Count); for (int i = 0; i < matches.Count; i++) { TreeNode node = new TreeNode(NodeString(i, matches[i].Value)); node.Tag = new HighlightInfo() { Index = matches[i].Index, Length = matches[i].Length }; // start from 1, because 0 is match itself for (int j = 1; j < matches[i].Groups.Count; j++) { TreeNode childNode = new TreeNode(NodeString(j, regex.GroupNameFromNumber(j), matches[i].Groups[j].Value)); childNode.Tag = new HighlightInfo() { Index = matches[i].Groups[j].Index, Length = matches[i].Groups[j].Length }; for (int k = 0; k < matches[i].Groups[j].Captures.Count; k++) { TreeNode childchildNode = new TreeNode(NodeString(k, matches[i].Groups[j].Captures[k].Value)); childchildNode.Tag = new HighlightInfo() { Index = matches[i].Groups[j].Captures[k].Index, Length = matches[i].Groups[j].Captures[k].Length }; childNode.Nodes.Add(childchildNode); } node.Nodes.Add(childNode); } nodesOfMatches.Add(node); } return nodesOfMatches.ToArray(); }
private static IList<Scope> GetCapturedMatches(Match regexMatch, CompiledMacro macro, IList<Scope> capturedMatches, Regex regex) { for (int i = 0; i < regexMatch.Groups.Count; i++) { if (regex.GroupNameFromNumber(i) != i.ToString()) continue; Group regexGroup = regexMatch.Groups[i]; string capture = macro.Captures[i]; if (regexGroup.Captures.Count == 0 || String.IsNullOrEmpty(capture)) continue; foreach (Capture regexCapture in regexGroup.Captures) AppendCapturedMatchesForRegexCapture(regexCapture, capture, capturedMatches); } return capturedMatches; }
/// <summary> /// Initializes a new instance of the <see cref="Request"/> class. /// </summary> /// <param name="fullrequest">The full request string.</param> public Request(string fullrequest, Regex rx) { HasSessionId = false; GET = new Hashtable(); POST = new Hashtable(); CLIENT = new Hashtable(); COOKIE = new Hashtable(); SESSION = new Hashtable(); string line = fullrequest.Substring(0, fullrequest.IndexOf("\r\n")); int firstspace = line.IndexOf(' ') + 1; RequestedPath = line.Substring(firstspace, line.LastIndexOf(' ') - firstspace); Match match = rx.Match(RequestedPath); for (int i = 1; i < match.Groups.Count; i++) { GET.Add(rx.GroupNameFromNumber(i), HttpUtility.UrlDecode(match.Groups[i].Value)); } Regex sessidrx = new Regex(@"ISESSION=([A-Z0-9]{16})", RegexOptions.Compiled); if (sessidrx.IsMatch(fullrequest)) { HasSessionId = true; Match m = sessidrx.Match(fullrequest); GroupCollection g = m.Groups; SessionId = g[1].Value; } if (line.Split(new char[] { ' ' })[0] == "POST") { Regex rx2 = new Regex(@"\&*([a-zA-Z0-9_]+)=([^\&]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase); MatchCollection Matches = rx2.Matches(fullrequest.Substring(fullrequest.IndexOf("\r\n\r\n")+4)); foreach (Match m in Matches) { GroupCollection groups = m.Groups; string val = groups[2].Value; if (val.StartsWith("&")) { val = val.Substring(1); } POST.Add(groups[1].Value, HttpUtility.UrlDecode(val)); } } }
public string Evaluate(string inputText, Regex regex) { var sb = new StringBuilder(); var groups = regex.GetGroupNames(); if (groups.Length > 1) { sb.AppendLine(string.Format("Groups: {0}", string.Join(", ", groups.Skip(1)))); sb.AppendLine(); } foreach (Match match in regex.Matches(inputText)) { sb.AppendLine(string.Format("Match: {0}", match.Value)); for (var i = 1; i < match.Groups.Count; i++) { var g = match.Groups[i]; if (g.Success) { sb.AppendLine(string.Format(" Group {0}: {1}", regex.GroupNameFromNumber(i), g.Value)); } } } return sb.ToString(); }
private void button1_Click(object sender, EventArgs e) { // Define a regular expression try { Regex rx = new Regex(txtRegex.Text, RegexOptions.Compiled | RegexOptions.IgnoreCase); // Find matches. MatchCollection matches = rx.Matches(txtSource.Text); txtMatch.Text = ""; foreach (Match match in matches) { // Report the number of matches found. //Console.WriteLine("{0} matches found in: {1} value: {2}\n", matches.Count, txtSource.Text, match.Groups[1].ToString()); //txtMatch.Text = match.Groups[1].ToString(); for (int i = 1; i < match.Groups.Count; i++) { var group = match.Groups[i]; if (group.Success) txtMatch.Text = txtMatch.Text + "Group: " + rx.GroupNameFromNumber(i) + " Value: " + match.Groups[i].ToString() + "\r\n"; } } } catch(Exception x) { // Catch the exception and display the error message. MessageBox.Show(x.Message, "Oops.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
private static DynamicDictionary GetParameters(Regex regex, IList<Group> matches) { dynamic data = new DynamicDictionary(); for (var i = 1; i <= matches.Count() - 1; i++) { data[regex.GroupNameFromNumber(i)] = matches[i].Value; } return data; }
private void UpdateResults() { treeResult.Items.Clear(); if (string.IsNullOrEmpty(txtRegex.Text)) return; Regex regex = null; try { regex = new Regex(txtRegex.Text); } catch (ArgumentException ex) { treeResult.Items.Add("Syntax error " + ex.Message); return; } var matches = regex.Matches(txtSubjectText.Text); if (matches.Count == 0) { treeResult.Items.Add("(no matches found)"); } else { int matchIndex = 0; foreach (Match match in matches) { var parent = new TreeViewItem() { Header = "Match " + matchIndex++, IsExpanded = true }; if (match.Success) { parent.Items.Add(GetCaptures(match.Captures)); int i = 0; var groups = new TreeViewItem() { Header = "Groups", IsExpanded = true }; foreach (Group group in match.Groups) { var node = new TreeViewItem() { Header = string.Format( "Group {0}{1}: {2}", i, (regex.GroupNameFromNumber(i) != i.ToString() ? " (?<" + regex.GroupNameFromNumber(i) + ">)" : ""), (group.Success ? group.Value : "(Not matched)") ), IsExpanded = true }; groups.Items.Add(node); i++; } parent.Items.Add(groups); } treeResult.Items.Add(parent); } } }
public override RouteData GetRouteData(HttpContextBase httpContext) { // 构造 regex domainRegex = CreateRegex(Domain); pathRegex = CreateRegex(Url); // 请求信息 string requestDomain = httpContext.Request.Headers["host"]; if (!string.IsNullOrEmpty(requestDomain)) { if (requestDomain.IndexOf(":") > 0) { requestDomain = requestDomain.Substring(0, requestDomain.IndexOf(":")); } } else { requestDomain = httpContext.Request.Url.Host; } string requestPath = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + httpContext.Request.PathInfo; // 匹配域名和路由 Match domainMatch = domainRegex.Match(requestDomain); Match pathMatch = pathRegex.Match(requestPath); // 路由数据 RouteData data = null; if ((domainMatch.Success && pathMatch.Success)) { //如果要访问的地址 与当前的路由配置中 域名或者路径都匹配的话 那么使用该条路由配置信息 data = new RouteData(this, RouteHandler); // 添加默认选项 if (Defaults != null) { foreach (KeyValuePair<string, object> item in Defaults) { data.Values[item.Key] = item.Value; if (item.Key.Equals("area") || item.Key.Equals("Namespaces")) { data.DataTokens[item.Key] = item.Value; } } } // 匹配域名路由 for (int i = 1; i < domainMatch.Groups.Count; i++) { Group group = domainMatch.Groups[i]; if (group.Success) { string key = domainRegex.GroupNameFromNumber(i); if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0)) { if (!string.IsNullOrEmpty(group.Value)) { data.Values[key] = group.Value; if (key.Equals("area")) { data.DataTokens[key] = group.Value; } } } } } // 匹配域名路径 for (int i = 1; i < pathMatch.Groups.Count; i++) { Group group = pathMatch.Groups[i]; if (group.Success) { string key = pathRegex.GroupNameFromNumber(i); if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0)) { if (!string.IsNullOrEmpty(group.Value)) { data.Values[key] = group.Value; if (key.Equals("area")) { data.DataTokens[key] = group.Value; } } } } } } return data; }
/// <summary> /// Gets the group name that corresponds to the specified group number. /// </summary> /// <param name="i">Group number to be converted to the corresponding group name.</param> /// <returns>String that contains the group name associated with the specified group number. If no group name matches <paramref name="i"/>, the method returns <see cref="string.Empty"/>.</returns> public string GroupNameFromNumber(int i) { return(_regex.GroupNameFromNumber(i)); }
void PerformQuery (string input, string pattern, string replacement, RegexOptions options) { try { Regex regex = new Regex (pattern, options); Application.Invoke (delegate { this.resultStore.Clear (); foreach (Match match in regex.Matches (input)) { TreeIter iter = this.resultStore.AppendValues (Stock.Find, String.Format (GettextCatalog.GetString("Match '{0}'"), match.Value), match.Index, match.Length); int i = 0; foreach (Group group in match.Groups) { TreeIter groupIter; if (group.Success) { groupIter = this.resultStore.AppendValues (iter, Stock.Apply, String.Format (GettextCatalog.GetString("Group '{0}':'{1}'"), regex.GroupNameFromNumber (i), group.Value), group.Index, group.Length); foreach (Capture capture in match.Captures) { this.resultStore.AppendValues (groupIter, null, String.Format (GettextCatalog.GetString("Capture '{0}'"), capture.Value), capture.Index, capture.Length); } } else { groupIter = this.resultStore.AppendValues (iter, Stock.Cancel, String.Format (GettextCatalog.GetString("Group '{0}' not found"), regex.GroupNameFromNumber (i)), -1, -1); } i++; } } if (!String.IsNullOrEmpty (replacement)) this.replaceResultTextview.Buffer.Text = regex.Replace (input, replacement); }); } catch (ThreadAbortException) { Thread.ResetAbort (); } catch (ArgumentException) { Application.Invoke (delegate { labelStatus.Text = GettextCatalog.GetString ("Invalid expression"); }); } finally { regexThread = null; Application.Invoke (delegate { SetButtonStart (GettextCatalog.GetString ("_Start Regular Expression"), "gtk-media-play"); }); } }
public override RouteData GetRouteData(HttpContextBase httpContext) { // Build regex domainRegex = CreateRegex(Domain); pathRegex = CreateRegex(Url); // Request information string requestDomain = httpContext.Request.Headers["host"]; if (!string.IsNullOrEmpty(requestDomain)) { if (requestDomain.IndexOf(":") > 0) { requestDomain = requestDomain.Substring(0, requestDomain.IndexOf(":")); } } else { requestDomain = httpContext.Request.Url.Host; } string requestPath = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + httpContext.Request.PathInfo; // Match domain and route Match domainMatch = domainRegex.Match(requestDomain); Match pathMatch = pathRegex.Match(requestPath); // Route data RouteData data = null; if (domainMatch.Success && pathMatch.Success) { data = new RouteData(this, RouteHandler); // Add defaults first if (Defaults != null) { foreach (KeyValuePair<string, object> item in Defaults) { data.Values[item.Key] = item.Value; } } // Iterate matching domain groups for (int i = 1; i < domainMatch.Groups.Count; i++) { Group group = domainMatch.Groups[i]; if (group.Success) { string key = domainRegex.GroupNameFromNumber(i); if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0)) { if (!string.IsNullOrEmpty(group.Value)) { data.Values[key] = group.Value; } } } } // Iterate matching path groups for (int i = 1; i < pathMatch.Groups.Count; i++) { Group group = pathMatch.Groups[i]; if (group.Success) { string key = pathRegex.GroupNameFromNumber(i); if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0)) { if (!string.IsNullOrEmpty(group.Value)) { data.Values[key] = group.Value; } } } } } return data; }
public void MultipleMatches() { Regex regex = new Regex (@"^(?'path'.*(\\|/)|(/|\\))(?'file'.*)$"); Match match = regex.Match (@"d:\Temp\SomeDir\SomeDir\bla.xml"); Assert.AreEqual (5, match.Groups.Count, "#1"); Assert.AreEqual ("1", regex.GroupNameFromNumber (1), "#2"); Assert.AreEqual ("2", regex.GroupNameFromNumber (2), "#3"); Assert.AreEqual ("path", regex.GroupNameFromNumber (3), "#4"); Assert.AreEqual ("file", regex.GroupNameFromNumber (4), "#5"); Assert.AreEqual ("\\", match.Groups [1].Value, "#6"); Assert.AreEqual (string.Empty, match.Groups [2].Value, "#7"); Assert.AreEqual (@"d:\Temp\SomeDir\SomeDir\", match.Groups [3].Value, "#8"); Assert.AreEqual ("bla.xml", match.Groups [4].Value, "#9"); }
private void ButtonMatch_Click(object sender, RoutedEventArgs e) { this.treeViewResult.Items.Clear(); Regex regex = null; try { regex = new Regex(GetExpressionText(), RegexOptions.Multiline); } catch (Exception ex) { this.treeViewResult.Items.Add(new TreeViewItem { Header = ex.Message, IsExpanded = true }); return; } MatchCollection matches = regex.Matches(this.textBoxMatches.Text); if (matches.Count > 0) { foreach (Match match in matches) { if (match.Success) { TreeViewItem matchTreeItem = new TreeViewItem { Header = NormalizeMatchValue(match.Value), IsExpanded = true, Tag = match }; this.treeViewResult.Items.Add(matchTreeItem); for (int i = 1; i < match.Groups.Count; i++) { string groupName = regex.GroupNameFromNumber(i); matchTreeItem.Items.Add(new TreeViewItem { Header = string.Format("{0}: '{1}'", groupName, NormalizeMatchValue(match.Groups[i].Value)), Tag = match.Groups[i] }); } } } } else { this.treeViewResult.Items.Add(new TreeViewItem { Header = "No results" }); } }
void PerformQuery (string input, string pattern, string replacement, RegexOptions options) { try { Regex regex = new Regex (pattern, options); Application.Invoke (delegate { this.resultStore.Clear (); var matches = regex.Matches (input); foreach (Match match in matches) { TreeIter iter = this.resultStore.AppendValues (Stock.Find, String.Format (GettextCatalog.GetString ("Match '{0}'"), match.Value), match.Index, match.Length); int i = 0; foreach (Group group in match.Groups) { TreeIter groupIter; if (group.Success) { groupIter = this.resultStore.AppendValues (iter, Stock.Apply, String.Format (GettextCatalog.GetString ("Group '{0}':'{1}'"), regex.GroupNameFromNumber (i), group.Value), group.Index, group.Length); foreach (Capture capture in match.Captures) { this.resultStore.AppendValues (groupIter, null, String.Format (GettextCatalog.GetString ("Capture '{0}'"), capture.Value), capture.Index, capture.Length); } } else { groupIter = this.resultStore.AppendValues (iter, Stock.Cancel, String.Format (GettextCatalog.GetString ("Group '{0}' not found"), regex.GroupNameFromNumber (i)), -1, -1); } i++; } } if (matches.Count == 0) { this.resultStore.AppendValues (Stock.Find, GettextCatalog.GetString ("No matches")); } if (this.expandMatches.Active) { this.resultsTreeview.ExpandAll (); } if (!String.IsNullOrEmpty (replacement)) this.replaceResultTextview.Buffer.Text = regex.Replace (input, replacement); }); } catch (ThreadAbortException) { Thread.ResetAbort (); } catch (ArgumentException) { Application.Invoke (delegate { Ide.IdeApp.Workbench.StatusBar.ShowError (GettextCatalog.GetString ("Invalid expression")); }); } finally { regexThread = null; } }
public void Instance_Deny_Unrestricted () { Regex r = new Regex (String.Empty); Assert.AreEqual (RegexOptions.None, r.Options, "Options"); Assert.IsFalse (r.RightToLeft, "RightToLeft"); Assert.AreEqual (1, r.GetGroupNames ().Length, "GetGroupNames"); Assert.AreEqual (1, r.GetGroupNumbers ().Length, "GetGroupNumbers"); Assert.AreEqual ("0", r.GroupNameFromNumber (0), "GroupNameFromNumber"); Assert.AreEqual (0, r.GroupNumberFromName ("0"), "GroupNumberFromName"); Assert.IsTrue (r.IsMatch (String.Empty), "IsMatch"); Assert.IsTrue (r.IsMatch (String.Empty, 0), "IsMatch2"); Assert.IsNotNull (r.Match (String.Empty), "Match"); Assert.IsNotNull (r.Match (String.Empty, 0), "Match2"); Assert.IsNotNull (r.Match (String.Empty, 0, 0), "Match3"); Assert.AreEqual (1, r.Matches (String.Empty).Count, "Matches"); Assert.AreEqual (1, r.Matches (String.Empty, 0).Count, "Matches2"); Assert.AreEqual (String.Empty, r.Replace (String.Empty, new MatchEvaluator (Evaluator)), "Replace"); Assert.AreEqual (String.Empty, r.Replace (String.Empty, new MatchEvaluator (Evaluator), 0), "Replace2"); Assert.AreEqual (String.Empty, r.Replace (String.Empty, new MatchEvaluator (Evaluator), 0, 0), "Replace3"); Assert.AreEqual (String.Empty, r.Replace (String.Empty, String.Empty), "Replace4"); Assert.AreEqual (String.Empty, r.Replace (String.Empty, String.Empty, 0), "Replace5"); Assert.AreEqual (String.Empty, r.Replace (String.Empty, String.Empty, 0, 0), "Replace6"); Assert.AreEqual (2, r.Split (String.Empty).Length, "Split"); Assert.AreEqual (2, r.Split (String.Empty, 0).Length, "Split2"); Assert.AreEqual (2, r.Split (String.Empty, 0, 0).Length, "Split3"); Assert.AreEqual (String.Empty, r.ToString (), "ToString"); }
private void FillTreeWithMatches(MatchCollection found, Regex CreatingRegexObject) { ClearTreeNodes(); foreach (Match m in found) { if (m.Value.Length > 0) { int ThisNode = AddTreeNode("[" + m.Value + "]", m, ICON_GROUP); if (m.Groups.Count > 1) { for (int i = 1; i < m.Groups.Count; i++) { string SubNodeText = CreatingRegexObject.GroupNameFromNumber(i) + ": [" + m.Groups[i].Value + "]"; AddSubNode(ThisNode, SubNodeText, m.Groups[i], i); //This bit of code puts in another level of nodes showing the captures for each group int Number = m.Groups[i].Captures.Count; if (Number > 1 /*&& AppContext.Instance.Settings.FillUnNamedCapturesInTree*/) { for (int j = 0; j < Number; j++) { TreeNode newNode = AddSubNode(ThisNode, m.Groups[i].Captures[j].Value, m.Groups[i].Captures[j], i, j); } } } } } } }
public override RouteData GetRouteData(HttpContextBase httpContext) { domainRegex = CreateRegex(Domain); pathRegex = CreateRegex(Url); string requestDomain = httpContext.Request.Headers["host"];//中国域名会编码,使用IdnMapping解码 if (!string.IsNullOrEmpty(requestDomain)) { if (requestDomain.IndexOf(":") > 0) { requestDomain = requestDomain.Substring(0, requestDomain.IndexOf(":")); } } else { requestDomain = httpContext.Request.Url.Host; } string requestPath = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + httpContext.Request.PathInfo; requestDomain = new System.Globalization.IdnMapping().GetUnicode(requestDomain);//中文域名解码 Match domainMatch = domainRegex.Match(requestDomain); Match pathMatch = pathRegex.Match(requestPath); RouteData data = null; if (domainMatch.Success && pathMatch.Success) { data = new RouteData(this, RouteHandler); if (Defaults != null) { foreach (KeyValuePair<string, object> item in Defaults) { data.Values[item.Key] = item.Value; } } for (int i = 1; i < domainMatch.Groups.Count; i++) { Group group = domainMatch.Groups[i]; if (group.Success) { string key = domainRegex.GroupNameFromNumber(i); if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0)) { if (!string.IsNullOrEmpty(group.Value)) { data.Values[key] = group.Value; } } } } for (int i = 1; i < pathMatch.Groups.Count; i++) { Group group = pathMatch.Groups[i]; if (group.Success) { string key = pathRegex.GroupNameFromNumber(i); if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0)) { if (!string.IsNullOrEmpty(group.Value)) { data.Values[key] = group.Value; } } } } foreach (var item in this.DataTokens) { data.DataTokens.Add(item.Key, item.Value); } } return data; }
/// <summary> /// 获取路由值 /// </summary> /// <param name="data">路由</param> /// <param name="match">正则匹配</param> /// <param name="regex">正则</param> private void GetRouteData(RouteData data, Match match, Regex regex) { // 匹配路径 for (var i = 1; i < match.Groups.Count; i++) { var group = match.Groups[i]; if (!group.Success) { continue; } var key = regex.GroupNameFromNumber(i); if (string.IsNullOrEmpty(key) || char.IsNumber(key, 0) || string.IsNullOrEmpty(group.Value)) { continue; } data.Values[key] = group.Value; } }
private static void Print(Regex RE, GroupCollection GC) { for (int i = 1; i < GC.Count; i++) { log.Info(RE.GroupNameFromNumber(i) + " = " + GC[i]); if (RE.GroupNameFromNumber(i) == "user") { object playerExists = Transaction.ExecuteScalar("select count(*) from players where name = '" + GC[i] + "'"); if (int.Parse(playerExists.ToString()) == 0) { Transaction.ExecuteNonQuery("insert into players (name) values ('" + GC[i] + "')"); } } } }
private static void AddGroupNameToResult(Regex regex,PhpArray matches, int i, Action<PhpArray, string> action) { // named group? var groupName = regex.GroupNameFromNumber(i); //remove sign from the beginning of the groupName groupName = groupName[0] == PerlRegExpConverter.GroupPrefix ? groupName.Remove(0, 1) : groupName; if (!String.IsNullOrEmpty(groupName) && groupName != i.ToString()) { action(matches, groupName); } }
private void UpdateResults() { if (null != RegexText && null != RegexTestString) { try { _Matches.Clear(); Regex r = new Regex(RegexText); if (r.IsMatch(RegexTestString)) { Match m = r.Match(RegexTestString); for (int i = 0; i < m.Groups.Count; i++) { _Matches.Add(new KeyValuePair<string, string>((null != r.GroupNameFromNumber(i) ? r.GroupNameFromNumber(i) : i.ToString()), m.Groups[i].Value)); } } } catch { _Matches.Clear(); } } else { _Matches.Clear(); } }
private static string GetGroupName(Regex regex, int index) { var groupName = regex.GroupNameFromNumber(index); if (groupName.StartsWith(PerlRegExpConverter.AnonymousGroupPrefix)) { // Anonymous groups: remove it altogether. Its purpose was to order it correctly. Debug.Assert(groupName.Substring(PerlRegExpConverter.AnonymousGroupPrefix.Length) == index.ToString(CultureInfo.InvariantCulture)); groupName = string.Empty; } else if (groupName[0] != PerlRegExpConverter.GroupPrefix) { // Indexed groups. Leave as-is. Debug.Assert(groupName == index.ToString(CultureInfo.InvariantCulture)); groupName = string.Empty; } else { // Named groups: remove prefix. groupName = (groupName[0] == PerlRegExpConverter.GroupPrefix ? groupName.Substring(1) : groupName); } return groupName; }
/// <summary> /// Executes the task. /// </summary> protected override void ExecuteTask() { Regex regex = null; try { regex = new Regex(Pattern, Options); } catch (ArgumentException ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1145"), Pattern), Location, ex); } Match match = regex.Match(Input); if (match == Match.Empty) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1144"), Pattern, Input), Location); } // we start the iteration at 1, since the collection of groups // always starts with a group which matches the entire input and // is named '0', this group is of no interest to us for (int i = 1; i < match.Groups.Count; i++) { string groupName = regex.GroupNameFromNumber(i); Log(Level.Verbose, "Setting property '{0}' to '{1}'.", groupName, match.Groups[groupName].Value); Properties[groupName] = match.Groups[groupName].Value; } }