protected Rule(string parsePattern) { RulePattern = new Regex(parsePattern, RegexOptions.Singleline); var regexGroupsAmount = RulePattern.GetGroupNumbers().Length; if (regexGroupsAmount != 4) throw new Exception(string.Format(IncorrectPatternMsg, this.GetType().FullName)); }
static int GetGroupNumbers(IntPtr L) { LuaScriptMgr.CheckArgsCount(L, 1); System.Text.RegularExpressions.Regex obj = (System.Text.RegularExpressions.Regex)LuaScriptMgr.GetNetObjectSelf(L, 1, "System.Text.RegularExpressions.Regex"); int[] o = obj.GetGroupNumbers(); LuaScriptMgr.PushArray(L, o); return(1); }
/// <summary> /// Gets the named groups. /// </summary> /// <param name="This">This Regex.</param> /// <returns>A dictionary with all named groups and their indexes.</returns> public static Dictionary <int, string> GetNamedGroups(this Regex This) { Contract.Requires(This != null); var groupNames = This.GetGroupNames(); var groupNumbers = This.GetGroupNumbers(); return(Enumerable.Range(0, Math.Min(groupNames.Length, groupNumbers.Length)).Where(i => groupNames[i] != groupNumbers[i].ToString("0")).ToDictionary(i => groupNumbers[i], i => groupNames[i])); }
public UriPattern(string template) { template = template.TrimEnd('*').ToUpperInvariant(); Tokens = GetTokens(template); TokenSet = new HashSet<string>(Tokens); TokensCount = Tokens.Length; var segments = BuildRegex(template); var finalPattern = EscapePattern.Replace(segments, PathGroup); TemplatePattern = new Regex(finalPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase); Groups = TemplatePattern.GetGroupNumbers().Length; }
public TrimMiddleProcessor(string trimFromStr) { if (!string.IsNullOrWhiteSpace(trimFromStr)) { trimMiddle = new Regex(trimFromStr, RegexOptions.Compiled | RegexOptions.Singleline); if (trimMiddle.GetGroupNumbers().Length < 2) { throw new ArgumentException("Regex must have at least two groups, exmaple: (group1)(group2)"); } } }
static public int GetGroupNumbers(IntPtr l) { try { System.Text.RegularExpressions.Regex self = (System.Text.RegularExpressions.Regex)checkSelf(l); var ret = self.GetGroupNumbers(); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
public Column(Config.Column column) { Name = column.Name; Select = column.Select; if (!String.IsNullOrEmpty(column.Match)) { Regex = new Regex(column.Match, RegexOptions.Compiled); if (Regex.GetGroupNumbers().Length != 2) { throw new Exception("Invalid regular expression pattern: " + column.Match + "\n The expression must contain exactly one group (in parentheses)"); } } }
public UriPattern(string template) { template = template.TrimEnd('*').ToUpperInvariant(); this.Template = template; Tokens = GetTokens(template); TokenMap = new Dictionary<string, int>(); for (int i = 0; i < Tokens.Length; i++) TokenMap[Tokens[i]] = i; TokensCount = Tokens.Length; if (TokensCount == 0 && !template.Contains("?") && !template.Contains("{")) ExtractMatcher = StaticExtractMatch; else ExtractMatcher = DynamicExtractMatch; var segments = BuildRegex(template); var finalPattern = EscapePattern.Replace(segments, PathGroup); TemplatePattern = new Regex(finalPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase); Groups = TemplatePattern.GetGroupNumbers().Length; }
public static void Main(string[] args) { //正则表达式的一般用法 Regex regex = new Regex(@"\w+=\w+"); Match match = regex.Match(" @@@@123=123="); //查询整个字符串 if (match.Success) { Console.WriteLine(match.Groups[0].Value); } //查询分组 int[] groupnums = regex.GetGroupNumbers(); while (match.Success) { Console.WriteLine(match.Groups[0].Value); match = match.NextMatch(); } }
public string ScanForTokens(string line, Regex pattern, string FS) { List<string> sb = new List<string>(); Match m = pattern.Match(line); // Only return submatches if found, otherwise return any matches. while (m.Success) { int[] gnums = pattern.GetGroupNumbers(); if (gnums.Length > 1) { for (int i = 1; i < gnums.Length; i++) { string token = m.Groups[gnums[i]].ToString(); sb.Add(token); } } else { // Only include the substring that was matched. sb.Add(m.Value); } m = m.NextMatch(); } return String.Join(FS, sb.ToArray()); }
public void Execute () { string result; for (int compiled = 0; compiled < 2; ++compiled) { RegexOptions real_options = (compiled == 1) ? (options | RegexOptions.Compiled) : options; try { Regex re = new Regex (pattern, real_options); int [] group_nums = re.GetGroupNumbers (); Match m = re.Match (input); if (m.Success) { result = "Pass."; for (int i = 0; i < m.Groups.Count; ++ i) { int gid = group_nums [i]; Group group = m.Groups [gid]; result += " Group[" + gid + "]="; foreach (Capture cap in group.Captures) result += "(" + cap.Index + "," + cap.Length + ")"; } } else { result = "Fail."; } } catch (Exception e) { error = e.Message + "\n" + e.StackTrace + "\n\n"; result = "Error."; } Assert.AreEqual (expected, result, "Matching input '{0}' against pattern '{1}' with options '{2}'", input, pattern, real_options); } }
/// <summary> /// Создание экземпляра раскрасивальщика с дополнительными опциями для регулярного выражения. /// </summary> /// <param name="name">Имя схемы</param> /// <param name="xmlSource">Исходный xml-поток</param> /// <param name="options">Regex опции</param> public CodeFormatter(string name, Stream xmlSource, RegexOptions options) { try { var regexString = new StringBuilder(); #pragma warning disable 618 var validatingReader = new XmlValidatingReader(new XmlTextReader(xmlSource)) { ValidationType = ValidationType.Schema }; #pragma warning restore 618 validatingReader.Schemas.Add(_xmlSchemas); var doc = new XmlDocument(); doc.Load(validatingReader); var namespaceManager = new XmlNamespaceManager(doc.NameTable); namespaceManager.AddNamespace("cc", "http://rsdn.ru/coloring"); // Поиск коневого элемента var root = doc.SelectSingleNode("cc:language", namespaceManager); // Установка regex опций, если есть Debug.Assert(root != null, "root != null"); if (root.Attributes != null && root.Attributes["options"] != null) regexString.Append(root.Attributes["options"].Value); // Выборка шаблонов var syntax = root.SelectNodes("cc:pattern", namespaceManager); Debug.Assert(syntax != null); for (var i = 0; i < syntax.Count; i++) { if (i > 0) regexString.Append('|'); Debug.Assert(syntax[i].Attributes != null, "syntax[i].Attributes"); regexString.AppendFormat("(?<{0}>", syntax[i].Attributes["name"].Value); var prefix = syntax[i].Attributes["prefix"] != null ? syntax[i].Attributes["prefix"].Value : null; var postfix = syntax[i].Attributes["postfix"] != null ? syntax[i].Attributes["postfix"].Value : null; // Выборка элементов шаблона var items = syntax[i].SelectNodes("cc:entry", namespaceManager); Debug.Assert(items != null); for (var j = 0; j < items.Count; j++) { if (j > 0) regexString.Append('|'); regexString.Append(prefix).Append(items[j].InnerText).Append(postfix); } regexString.Append(')'); } // Создание регулярного выражения ColorerRegex = new Regex(regexString.ToString(), options); // Чтение параметров регулярного выражения CountGroups = ColorerRegex.GetGroupNumbers().Length; var numbers = ColorerRegex.GetGroupNumbers(); var names = ColorerRegex.GetGroupNames(); GroupNames = new string[numbers.Length]; for (var i = 0; i < numbers.Length; i++) GroupNames[numbers[i]] = names[i]; } catch (XmlException xmlException) { throw new FormatterException( string.Format("Language color pattern source xml stream is not valid:{0} - {1}", name, xmlException.Message), xmlException); } catch (XmlSchemaException schemaException) { throw new FormatterException( string.Format("Language color pattern source xml stream is not valid:{0} - {1}", name, schemaException.Message), schemaException); } }
public LSL_String llHTTPRequest(string url, LSL_List parameters, string body) { // Partial implementation: support for parameter flags needed // see http://wiki.secondlife.com/wiki/LlHTTPRequest // parameter flags support are implemented in ScriptsHttpRequests.cs // in StartHttpRequest m_host.AddScriptLPS(1); IHttpRequestModule httpScriptMod = m_ScriptEngine.World.RequestModuleInterface<IHttpRequestModule>(); List<string> param = new List<string>(); bool ok; Int32 flag; for (int i = 0; i < parameters.Data.Length; i += 2) { ok = Int32.TryParse(parameters.Data[i].ToString(), out flag); if (!ok || flag < 0 || flag > (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE) { Error("llHTTPRequest", "Parameter " + i.ToString() + " is an invalid flag"); } param.Add(parameters.Data[i].ToString()); //Add parameter flag if (flag != (int)HttpRequestConstants.HTTP_CUSTOM_HEADER) { param.Add(parameters.Data[i+1].ToString()); //Add parameter value } else { //Parameters are in pairs and custom header takes //arguments in pairs so adjust for header marker. ++i; //Maximum of 8 headers are allowed based on the //Second Life documentation for llHTTPRequest. for (int count = 1; count <= 8; ++count) { //Enough parameters remaining for (another) header? if (parameters.Data.Length - i < 2) { //There must be at least one name/value pair for custom header if (count == 1) Error("llHTTPRequest", "Missing name/value for custom header at parameter " + i.ToString()); break; } if (HttpStandardHeaders.Contains(parameters.Data[i].ToString(), StringComparer.OrdinalIgnoreCase)) Error("llHTTPRequest", "Name is invalid as a custom header at parameter " + i.ToString()); param.Add(parameters.Data[i].ToString()); param.Add(parameters.Data[i+1].ToString()); //Have we reached the end of the list of headers? //End is marked by a string with a single digit. if (i+2 >= parameters.Data.Length || Char.IsDigit(parameters.Data[i].ToString()[0])) { break; } i += 2; } } } Vector3 position = m_host.AbsolutePosition; Vector3 velocity = m_host.Velocity; Quaternion rotation = m_host.RotationOffset; string ownerName = String.Empty; ScenePresence scenePresence = World.GetScenePresence(m_host.OwnerID); if (scenePresence == null) ownerName = resolveName(m_host.OwnerID); else ownerName = scenePresence.Name; RegionInfo regionInfo = World.RegionInfo; Dictionary<string, string> httpHeaders = new Dictionary<string, string>(); string shard = "OpenSim"; IConfigSource config = m_ScriptEngine.ConfigSource; if (config.Configs["Network"] != null) { shard = config.Configs["Network"].GetString("shard", shard); } httpHeaders["X-SecondLife-Shard"] = shard; httpHeaders["X-SecondLife-Object-Name"] = m_host.Name; httpHeaders["X-SecondLife-Object-Key"] = m_host.UUID.ToString(); httpHeaders["X-SecondLife-Region"] = string.Format("{0} ({1}, {2})", regionInfo.RegionName, regionInfo.RegionLocX, regionInfo.RegionLocY); httpHeaders["X-SecondLife-Local-Position"] = string.Format("({0:0.000000}, {1:0.000000}, {2:0.000000})", position.X, position.Y, position.Z); httpHeaders["X-SecondLife-Local-Velocity"] = string.Format("({0:0.000000}, {1:0.000000}, {2:0.000000})", velocity.X, velocity.Y, velocity.Z); httpHeaders["X-SecondLife-Local-Rotation"] = string.Format("({0:0.000000}, {1:0.000000}, {2:0.000000}, {3:0.000000})", rotation.X, rotation.Y, rotation.Z, rotation.W); httpHeaders["X-SecondLife-Owner-Name"] = ownerName; httpHeaders["X-SecondLife-Owner-Key"] = m_host.OwnerID.ToString(); string userAgent = config.Configs["Network"].GetString("user_agent", null); if (userAgent != null) httpHeaders["User-Agent"] = userAgent; string authregex = @"^(https?:\/\/)(\w+):(\w+)@(.*)$"; Regex r = new Regex(authregex); int[] gnums = r.GetGroupNumbers(); Match m = r.Match(url); if (m.Success) { for (int i = 1; i < gnums.Length; i++) { //System.Text.RegularExpressions.Group g = m.Groups[gnums[i]]; //CaptureCollection cc = g.Captures; } if (m.Groups.Count == 5) { httpHeaders["Authorization"] = String.Format("Basic {0}", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(m.Groups[2].ToString() + ":" + m.Groups[3].ToString()))); url = m.Groups[1].ToString() + m.Groups[4].ToString(); } } UUID reqID = httpScriptMod.StartHttpRequest(m_host.LocalId, m_item.ItemID, url, param, httpHeaders, body); if (reqID != UUID.Zero) return reqID.ToString(); else return null; }
/// <summary> /// Handles the CellEndEdit of the <see cref="DataGridView"/>. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DgvColumnsCellEndEdit(object sender, DataGridViewCellEventArgs e) { // Edit and delete is only possible if the cell is not in edit mode. UpdateEditButtons(); if (e.ColumnIndex == 1 && e.RowIndex > 0) { string valueToValidate = dgvColumns.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); if (!string.IsNullOrEmpty(valueToValidate)) { try { Regex validationRgx = new Regex(valueToValidate); if (validationRgx.GetGroupNumbers().Length == 1) { dgvColumns.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = string.Format( "({0})" , valueToValidate); } } catch { // Catch all invalid input values. } } } }
public NmpArray ExtractSubexpressions( string regExStr, int maxItems ) { // ****** NmpArray array = new NmpArray(); try { Regex rx = new Regex( regExStr ); MatchCollection mc = rx.Matches( theString ); // // find all matches for a regular expression and for each one return an // array of all subexpression whether captured or no, subexpressions that // are not captured (such as alterations that don't match) will be returned // as the empty string // // so either return a List<string []> or // string [] groupNames = rx.GetGroupNames(); int [] groupIndexes = rx.GetGroupNumbers(); int matchIndex = 0; foreach( Match match in mc ) { NmpArray subExpressions = new NmpArray(); for( int iGroup = 0; iGroup < match.Groups.Count; iGroup++ ) { string key; if( 0 == iGroup ) { key = "match"; } else { if( string.IsNullOrEmpty(groupNames[iGroup]) ) { continue; } key = groupNames[ iGroup ]; } // ****** subExpressions.Add( key, match.Groups[ iGroup ].Value ); } // // match.Value may not be unique // array.AddArray( (matchIndex++).ToString(), subExpressions ); // // note: we are NOT inhibiting Matches from generating as many matches as it // can, only limiting the number we return // if( 0 == --maxItems ) { break; } } } catch ( ArgumentException ex ) { throw ex; } // ****** return array; }
/// <summary> /// Returns a table of catch group numbers that correspond to the group names in a table. /// </summary> /// <returns>Table of integers of group numbers.</returns> public int[] GetGroupNumbers() { return(_regex.GetGroupNumbers()); }
public LSL_String llHTTPRequest(string url, LSL_List parameters, string body) { // Partial implementation: support for parameter flags needed // see http://wiki.secondlife.com/wiki/LlHTTPRequest // parameter flags support are implemented in ScriptsHttpRequests.cs // in StartHttpRequest m_host.AddScriptLPS(1); IHttpRequestModule httpScriptMod = m_ScriptEngine.World.RequestModuleInterface<IHttpRequestModule>(); List<string> param = new List<string>(); foreach (object o in parameters.Data) { param.Add(o.ToString()); } Vector3 position = m_host.AbsolutePosition; Vector3 velocity = m_host.Velocity; Quaternion rotation = m_host.RotationOffset; string ownerName = String.Empty; ScenePresence scenePresence = World.GetScenePresence(m_host.OwnerID); if (scenePresence == null) ownerName = resolveName(m_host.OwnerID); else ownerName = scenePresence.Name; RegionInfo regionInfo = World.RegionInfo; Dictionary<string, string> httpHeaders = new Dictionary<string, string>(); string shard = "OpenSim"; IConfigSource config = m_ScriptEngine.ConfigSource; if (config.Configs["Network"] != null) { shard = config.Configs["Network"].GetString("shard", shard); } httpHeaders["X-SecondLife-Shard"] = shard; httpHeaders["X-SecondLife-Object-Name"] = m_host.Name; httpHeaders["X-SecondLife-Object-Key"] = m_host.UUID.ToString(); httpHeaders["X-SecondLife-Region"] = string.Format("{0} ({1}, {2})", regionInfo.RegionName, regionInfo.RegionLocX, regionInfo.RegionLocY); httpHeaders["X-SecondLife-Local-Position"] = string.Format("({0:0.000000}, {1:0.000000}, {2:0.000000})", position.X, position.Y, position.Z); httpHeaders["X-SecondLife-Local-Velocity"] = string.Format("({0:0.000000}, {1:0.000000}, {2:0.000000})", velocity.X, velocity.Y, velocity.Z); httpHeaders["X-SecondLife-Local-Rotation"] = string.Format("({0:0.000000}, {1:0.000000}, {2:0.000000}, {3:0.000000})", rotation.X, rotation.Y, rotation.Z, rotation.W); httpHeaders["X-SecondLife-Owner-Name"] = ownerName; httpHeaders["X-SecondLife-Owner-Key"] = m_host.OwnerID.ToString(); string userAgent = config.Configs["Network"].GetString("user_agent", null); if (userAgent != null) httpHeaders["User-Agent"] = userAgent; string authregex = @"^(https?:\/\/)(\w+):(\w+)@(.*)$"; Regex r = new Regex(authregex); int[] gnums = r.GetGroupNumbers(); Match m = r.Match(url); if (m.Success) { for (int i = 1; i < gnums.Length; i++) { //System.Text.RegularExpressions.Group g = m.Groups[gnums[i]]; //CaptureCollection cc = g.Captures; } if (m.Groups.Count == 5) { httpHeaders["Authorization"] = String.Format("Basic {0}", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(m.Groups[2].ToString() + ":" + m.Groups[3].ToString()))); url = m.Groups[1].ToString() + m.Groups[4].ToString(); } } UUID reqID = httpScriptMod.StartHttpRequest(m_host.LocalId, m_item.ItemID, url, param, httpHeaders, body); if (reqID != UUID.Zero) return reqID.ToString(); else return null; }
public void Execute () { //We do not support RightToLeft, so skip if ((options & RegexOptions.RightToLeft) > 0) return; string result; for (int compiled = 0; compiled < 2; ++compiled) { RegexOptions real_options = (compiled == 1) ? (options | RegexOptions.Compiled) : options; try { Regex re = new Regex(pattern, real_options); int[] group_nums = re.GetGroupNumbers(); Match m = re.Match(input); if (m.Success) { result = "Pass."; for (int i = 0; i < m.Groups.Count; ++ i) { int gid = group_nums[i]; Group group = m.Groups[gid]; result += " Group[" + gid + "]="; foreach (Capture cap in group.Captures) result += "(" + cap.Index + "," + cap.Length + ")"; } } else { result = "Fail."; } } catch (NotSupportedException e) { //we do not support conditions. skip if (e.Message.StartsWith("Conditions")) return; result = "NotSupportedException."; } catch (Exception e) { error = e.Message + "\n" + e.StackTrace + "\n\n"; result = "Error."; } //if (expected.StartsWith("Fail.") || expected.StartsWith("Error.")) { Assert.AreEqual (expected, result, "Matching input '{0}' against pattern '{1}' with options '{2}'", input, pattern, real_options); } } }
private static string findMatchedGroupName(Regex regex, Match match) { string[] names = regex.GetGroupNames(); int[] numbers = regex.GetGroupNumbers(); for (int i = 1; i < numbers.Length; i++) if (match.Groups[numbers[i]].Success) return names[i]; throw null; }
public static void matchMappingArtifacts(BuildArtifactsMapping mapping, string projectDirectory, Dictionary<string, string> resultMap) { string rootDirectory = BuildArtifactsMapping.getRootDirectory(mapping); /*Incase we have none relative pattern, we need to add the project path for the * regular expression not to recognize it as part of the capturing groups. */ //if (String.IsNullOrWhiteSpace(rootDirectory) || !System.IO.Path.IsPathRooted(rootDirectory)) if (!System.IO.Path.IsPathRooted(rootDirectory)) { mapping.input = projectDirectory + "\\" + mapping.input; rootDirectory = projectDirectory + "\\" + rootDirectory; } if (Directory.Exists(rootDirectory) || File.Exists(rootDirectory)) { IEnumerable<string> fileList; //Incase we have a path with a file if (File.Exists(rootDirectory)) { fileList = new string[] { rootDirectory }; } else { fileList = Directory.GetFiles(rootDirectory, "*.*", SearchOption.AllDirectories); } string regexNormalize = NormalizeRegexInput(mapping); Regex regex = new Regex(regexNormalize); int inputGroupsNum = regex.GetGroupNumbers().Length - 1; ISet<Int32> placeHoldersSet = BuildArtifactsMapping.getPlaceHoldersList(mapping, inputGroupsNum); foreach (string file in fileList) { Match fileMatcher = regex.Match(file); if (fileMatcher.Success) { /* In case we didn't receive an output pattern, * the target will be the root of the repository */ if (String.IsNullOrWhiteSpace(mapping.output)) { FileInfo fileInfo = new FileInfo(file); resultMap.Add(file, fileInfo.Name); } else { List<string> replacementList = new List<string>(); string repositoryPath = mapping.output; foreach (int groupIndex in placeHoldersSet) { repositoryPath = repositoryPath.Replace("$" + groupIndex, fileMatcher.Groups[groupIndex].Value); } if (!resultMap.ContainsKey(file)) resultMap.Add(file, repositoryPath); } } } } }
void GroupNumbers_1 (string s, int n) { Regex r = new Regex (s); int [] grps = r.GetGroupNumbers (); Assert.AreEqual (n, grps.Length, "#1:" + r); int sum = 0; for (int i = 0; i < grps.Length; ++i) { sum += grps [i]; // group numbers are unique for (int j = 0; j < i; ++j) Assert.IsTrue (grps [i] != grps [j], "#2:" + r + " (" + i + "," + j + ")"); } // no gaps in group numbering Assert.AreEqual ((n * (n - 1)) / 2, sum, "#3:" + r); }
/// <summary> /// This is the core of the app. The RegEx execution and processing function. /// It's being run on a separated thread. /// </summary> private void AsyncTest() { int rtbSelectionStart = int.MinValue; int rtbSelectionLength = int.MinValue; int matchesFound = 0; int matchesProcessed = 0; DateTime startMoment = DateTime.Now; // Every line in this function is susceptible of a ThreadAbortException // Which is how the user is able to stop it. try { // Adjustments in the UI statusStatusBarPanel.Text = "Making UI Adjustments..."; testButton.Text = RUNNING_MODE_BUTTON_TEXT; matchesStatusBarPanel.Text = string.Empty; executionTimeStatusBarPanel.Text = string.Empty; // Create the options object based on the UI checkboxes statusStatusBarPanel.Text = "Configuring the RegEx engine..."; RegexOptions regexOptions = new RegexOptions(); if (ignoreCaseCheckBox.Checked) regexOptions |= RegexOptions.IgnoreCase; if (cultureInvariantCheckBox.Checked) regexOptions |= RegexOptions.CultureInvariant; if (multiLineCheckBox.Checked) regexOptions |= RegexOptions.Multiline; if (singleLineCheckBox.Checked) regexOptions |= RegexOptions.Singleline; if (indentedInputCheckBox.Checked) regexOptions |= RegexOptions.IgnorePatternWhitespace; statusStatusBarPanel.Text = "Creating the RegEx Engine and parsing the RegEx string..."; // Creates the RegEx engine passing the RegEx string and the options object Regex regex = new Regex(regExTextBox.Text, regexOptions); statusStatusBarPanel.Text = "Evaluating the RegEx against the Test Text..."; // This executes the Regex and collects the results // The execution isn't done until a member of the matchCollection is read. // So I read the Count property for the regex to really execute from start to finish MatchCollection matchCollection = regex.Matches(textRichTextBox.Text); matchesFound = matchCollection.Count; // Also do the RegEx replacement if the user asked for it if (replaceModeCheckBox.Checked) { statusStatusBarPanel.Text = "Evaluating the RegEx Replace against the Test Text..."; resultsRichTextBox.Text = regex.Replace(textRichTextBox.Text, repExTextBox.Text); } statusStatusBarPanel.Text = "Preparing the Results grid..."; // Setup the results ListView resultListView.Items.Clear(); for (int i = resultListView.Columns.Count; i > 3; i--) //Skip the first 3 columns resultListView.Columns.RemoveAt(i-1); // Add the Capture Group columns to the Results ListView int[] groupNumbers = regex.GetGroupNumbers(); string[] groupNames = regex.GetGroupNames(); string groupName = null; foreach (int groupNumber in groupNumbers) { if (groupNumber > 0) { groupName = "Group " + groupNumber; if (groupNames[groupNumber] != groupNumber.ToString()) groupName += " (" + groupNames[groupNumber] + ")"; resultListView.Columns.Add(groupName, 100, HorizontalAlignment.Left); } } // Store/Backup the user's cursor and selection on the RichTextBox rtbSelectionStart = textRichTextBox.SelectionStart; rtbSelectionLength = textRichTextBox.SelectionLength; // This pauses the drawing to speed-up the work textRichTextBox.SuspendLayout(); resultListView.SuspendLayout(); resultListView.BeginUpdate(); // Reset previous highligths in the RichTextBox and save current position. textRichTextBox.SelectAll(); textRichTextBox.SelectionColor = Color.Black; statusStatusBarPanel.Text = "Processing the " + matchesFound + " matchs..."; // Process each of the Matches! foreach (Match match in matchCollection) { //Add it to the grid ListViewItem lvi = resultListView.Items.Add(match.ToString()); lvi.SubItems.Add(match.Index.ToString()); lvi.SubItems.Add(match.Length.ToString()); for (int c = 1; c < match.Groups.Count; c++) { Group group = match.Groups[c]; if (group.Captures.Count == 1) lvi.SubItems.Add(group.Value); else { StringBuilder capturedValues = new StringBuilder(); foreach (Capture capture in group.Captures) { if (capturedValues.Length > 0) capturedValues.Append(" ¦ "); capturedValues.Append(capture.Value); } lvi.SubItems.Add(capturedValues.ToString()); } } //Highligth the match in the RichTextBox textRichTextBox.Select(match.Index, match.Length); textRichTextBox.SelectionColor = Color.Red; matchesProcessed++; } statusStatusBarPanel.Text = "Test success."; } catch (ThreadAbortException) { statusStatusBarPanel.Text = "Test aborted by the user."; } catch (Exception e) { statusStatusBarPanel.Text = "Test aborted by an error."; // Any other Exception is shown to the user MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { // Restore the btnText functionality testButton.Text = STOPPED_MODE_BUTTON_TEXT; // Restore RichTextBox's cursor position to the original user's position if (rtbSelectionStart != int.MinValue && rtbSelectionLength != int.MinValue) textRichTextBox.Select(rtbSelectionStart, rtbSelectionLength); if (matchesProcessed == matchesFound) matchesStatusBarPanel.Text = string.Format("{0} match(es).", matchesProcessed); else matchesStatusBarPanel.Text = string.Format("{0} match(es) of {1} found.", matchesProcessed, matchesFound); // Calculate execution time TimeSpan executionTimeSpan = DateTime.Now.Subtract(startMoment); if (executionTimeSpan.TotalHours > 1) executionTimeStatusBarPanel.Text = string.Format("{0} hs.", executionTimeSpan.TotalHours.ToString("##.##")); else if (executionTimeSpan.TotalMinutes > 1) executionTimeStatusBarPanel.Text = string.Format("{0} mins.", executionTimeSpan.TotalMinutes.ToString("##.##")); else if (executionTimeSpan.TotalSeconds > 1) executionTimeStatusBarPanel.Text = string.Format("{0} s.", executionTimeSpan.TotalSeconds.ToString("##.##")); else if (executionTimeSpan.TotalMilliseconds > 1) executionTimeStatusBarPanel.Text = string.Format("{0} ms.", executionTimeSpan.TotalMilliseconds.ToString("#")); // This reverts the rendering of the controls (turned off for performance) resultListView.EndUpdate(); resultListView.ResumeLayout(); textRichTextBox.ResumeLayout(); } }
public LSL_String llHTTPRequest(string url, LSL_List parameters, string body) { // Partial implementation: support for parameter flags needed // see http://wiki.secondlife.com/wiki/LlHTTPRequest // parameter flags support are implemented in ScriptsHttpRequests.cs // in StartHttpRequest m_host.AddScriptLPS(1); IHttpRequestModule httpScriptMod = m_ScriptEngine.World.RequestModuleInterface<IHttpRequestModule>(); List<string> param = new List<string>(); bool ok; Int32 flag; for (int i = 0; i < parameters.Data.Length; i += 2) { ok = Int32.TryParse(parameters.Data[i].ToString(), out flag); if (!ok || flag < 0 || flag > (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE) { Error("llHTTPRequest", "Parameter " + i.ToString() + " is an invalid flag"); } param.Add(parameters.Data[i].ToString()); //Add parameter flag if (flag != (int)HttpRequestConstants.HTTP_CUSTOM_HEADER) { param.Add(parameters.Data[i+1].ToString()); //Add parameter value } else { //Parameters are in pairs and custom header takes //arguments in pairs so adjust for header marker. ++i; //Maximum of 8 headers are allowed based on the //Second Life documentation for llHTTPRequest. for (int count = 1; count <= 8; ++count) { //Enough parameters remaining for (another) header? if (parameters.Data.Length - i < 2) { //There must be at least one name/value pair for custom header if (count == 1) Error("llHTTPRequest", "Missing name/value for custom header at parameter " + i.ToString()); break; } if (HttpStandardHeaders.Contains(parameters.Data[i].ToString(), StringComparer.OrdinalIgnoreCase)) Error("llHTTPRequest", "Name is invalid as a custom header at parameter " + i.ToString()); param.Add(parameters.Data[i].ToString()); param.Add(parameters.Data[i+1].ToString()); //Have we reached the end of the list of headers? //End is marked by a string with a single digit. if (i+2 >= parameters.Data.Length || Char.IsDigit(parameters.Data[i].ToString()[0])) { break; } i += 2; } } } Vector3 position = m_host.AbsolutePosition; Vector3 velocity = m_host.Velocity; Quaternion rotation = m_host.RotationOffset; string ownerName = String.Empty; ScenePresence scenePresence = World.GetScenePresence(m_host.OwnerID); if (scenePresence == null) ownerName = resolveName(m_host.OwnerID); else ownerName = scenePresence.Name; RegionInfo regionInfo = World.RegionInfo; Dictionary<string, string> httpHeaders = new Dictionary<string, string>(); string shard = "OpenSim"; IConfigSource config = m_ScriptEngine.ConfigSource; if (config.Configs["Network"] != null) { shard = config.Configs["Network"].GetString("shard", shard); } httpHeaders["X-SecondLife-Shard"] = shard; httpHeaders["X-SecondLife-Object-Name"] = m_host.Name; httpHeaders["X-SecondLife-Object-Key"] = m_host.UUID.ToString(); httpHeaders["X-SecondLife-Region"] = string.Format("{0} ({1}, {2})", regionInfo.RegionName, regionInfo.RegionLocX, regionInfo.RegionLocY); httpHeaders["X-SecondLife-Local-Position"] = string.Format("({0:0.000000}, {1:0.000000}, {2:0.000000})", position.X, position.Y, position.Z); httpHeaders["X-SecondLife-Local-Velocity"] = string.Format("({0:0.000000}, {1:0.000000}, {2:0.000000})", velocity.X, velocity.Y, velocity.Z); httpHeaders["X-SecondLife-Local-Rotation"] = string.Format("({0:0.000000}, {1:0.000000}, {2:0.000000}, {3:0.000000})", rotation.X, rotation.Y, rotation.Z, rotation.W); httpHeaders["X-SecondLife-Owner-Name"] = ownerName; httpHeaders["X-SecondLife-Owner-Key"] = m_host.OwnerID.ToString(); string userAgent = config.Configs["Network"].GetString("user_agent", null); if (userAgent != null) httpHeaders["User-Agent"] = userAgent; // See if the URL contains any header hacks string[] urlParts = url.Split(new char[] {'\n'}); if (urlParts.Length > 1) { // Iterate the passed headers and parse them for (int i = 1 ; i < urlParts.Length ; i++ ) { // The rest of those would be added to the body in SL. // Let's not do that. if (urlParts[i] == String.Empty) break; // See if this could be a valid header string[] headerParts = urlParts[i].Split(new char[] {':'}, 2); if (headerParts.Length != 2) continue; string headerName = headerParts[0].Trim(); string headerValue = headerParts[1].Trim(); // Filter out headers that could be used to abuse // another system or cloak the request if (headerName.ToLower() == "x-secondlife-shard" || headerName.ToLower() == "x-secondlife-object-name" || headerName.ToLower() == "x-secondlife-object-key" || headerName.ToLower() == "x-secondlife-region" || headerName.ToLower() == "x-secondlife-local-position" || headerName.ToLower() == "x-secondlife-local-velocity" || headerName.ToLower() == "x-secondlife-local-rotation" || headerName.ToLower() == "x-secondlife-owner-name" || headerName.ToLower() == "x-secondlife-owner-key" || headerName.ToLower() == "connection" || headerName.ToLower() == "content-length" || headerName.ToLower() == "from" || headerName.ToLower() == "host" || headerName.ToLower() == "proxy-authorization" || headerName.ToLower() == "referer" || headerName.ToLower() == "trailer" || headerName.ToLower() == "transfer-encoding" || headerName.ToLower() == "via" || headerName.ToLower() == "authorization") continue; httpHeaders[headerName] = headerValue; } // Finally, strip any protocol specifier from the URL url = urlParts[0].Trim(); int idx = url.IndexOf(" HTTP/"); if (idx != -1) url = url.Substring(0, idx); } string authregex = @"^(https?:\/\/)(\w+):(\w+)@(.*)$"; Regex r = new Regex(authregex); int[] gnums = r.GetGroupNumbers(); Match m = r.Match(url); if (m.Success) { for (int i = 1; i < gnums.Length; i++) { //System.Text.RegularExpressions.Group g = m.Groups[gnums[i]]; //CaptureCollection cc = g.Captures; } if (m.Groups.Count == 5) { httpHeaders["Authorization"] = String.Format("Basic {0}", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(m.Groups[2].ToString() + ":" + m.Groups[3].ToString()))); url = m.Groups[1].ToString() + m.Groups[4].ToString(); } } HttpInitialRequestStatus status; UUID reqID = httpScriptMod.StartHttpRequest(m_host.LocalId, m_item.ItemID, url, param, httpHeaders, body, out status); if (status == HttpInitialRequestStatus.DISALLOWED_BY_FILTER) Error("llHttpRequest", string.Format("Request to {0} disallowed by filter", url)); if (reqID != UUID.Zero) return reqID.ToString(); else return null; }
public static string Replace(string pattern, string replacement, string str) { PhpException.FunctionDeprecated("ereg_replace"); try { // convert Posix pattern to .NET regular expression and create regular expression object Regex r = new Regex(ConvertPosix2DotNetExpr(pattern)); // convert Posix replacement to .NET regular expression // (there may be \\digit references to pattern) and replace return r.Replace(str, ConvertPosix2DotNetRepl(replacement, r.GetGroupNumbers())); } catch (PhpException) { // PhpExceptions rethrow immediately throw; } catch (System.Exception e) { // all other exceptions convert to PhpException, we want to handle they in the same way // (display to user in web browser etc.) PhpException.Throw(PhpError.Warning, e.Message); return null; } }
/// <summary> /// Perform Regular Expression Test /// </summary> private void DoTest() { // Setup options RegexOptions ro = new RegexOptions(); if (mnuIgnore.Checked) ro = ro | RegexOptions.IgnoreCase; if (mnuMultiLine.Checked) ro = ro | RegexOptions.Multiline; ro = ro | RegexOptions.IgnorePatternWhitespace; // Create Regular Expression Engine Regex re = null; MatchCollection mc = null; try { string reg = txtRegEx.Text; if (txtRegEx.SelectionLength > 0) reg = txtRegEx.SelectedText; //reg = reg.Replace("\r\n", "").Replace("\n", "").Replace("\t", ""); re = new Regex(reg, ro); mc = re.Matches(rtbText.Text); } catch (Exception ex){ MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Setup ListView int[] ag = re.GetGroupNumbers(); lvResult.Clear(); lvResult.Columns.Add("Match", 435, HorizontalAlignment.Left); lvResult.Columns.Add("Position", 87, HorizontalAlignment.Left); lvResult.Columns.Add("Length", 98, HorizontalAlignment.Left); foreach(int c in ag) { if (c > 0) lvResult.Columns.Add("Group " + c.ToString(), 100, HorizontalAlignment.Left); } lvResult.Items.Clear(); // Setup RichTextBox rtbText.HideSelection = true; rtbText.SelectAll(); rtbText.SelectionColor = Color.Black; // Match! foreach(Match m in mc) { ListViewItem lvi = lvResult.Items.Add(m.ToString()); lvi.SubItems.Add(m.Index.ToString()); lvi.SubItems.Add(m.Length.ToString()); for (int c=1; c<m.Groups.Count; c++) { lvi.SubItems.Add(m.Groups[c].Value); } rtbText.Select(m.Index, m.Length); rtbText.SelectionColor = Color.Red; } // Reset RichTextBox rtbText.Select(0,0); rtbText.SelectionColor = Color.Black; // Show matching count sbpMatchCount.Text = "Match count: " + mc.Count.ToString(); }
/// <summary> /// creates a new PatternTokenizer returning tokens from group (-1 for split functionality) </summary> public PatternTokenizer(AttributeFactory factory, TextReader input, Regex pattern, int group) : base(factory, input) { this.termAtt = AddAttribute<ICharTermAttribute>(); this.offsetAtt = AddAttribute<IOffsetAttribute>(); this.group = group; // Use "" instead of str so don't consume chars // (fillBuffer) from the input on throwing IAE below: this.matcher = pattern.Match(""); this.pattern = pattern; // confusingly group count depends ENTIRELY on the pattern but is only accessible via matcher var groupCount = pattern.GetGroupNumbers().Length; if (group >= 0 && group > groupCount) { throw new System.ArgumentException("invalid group specified: pattern only has: " + groupCount + " capturing groups"); } }
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 Foo() { string text = "abracadabra1abracadabra2abracadabra3"; string pat = @"(abra(cad)?)+"; Regex r = new Regex(pat); //获得组号码的清单 int[] gnums = r.GetGroupNumbers(); //首次匹配 Match m = r.Match(text); while (m.Success) { //从组1开始 for (int i = 1; i < gnums.Length; i++) { Group g = m.Groups[gnums[i]]; //获得这次匹配的组 Console.WriteLine("Group" + gnums[i] + "=[" + g.ToString() + "]"); //计算这个组的起始位置和长度 CaptureCollection cc = g.Captures; for (int j = 0; j < cc.Count; j++) { Capture c = cc[j]; Console.WriteLine(" Capture" + j + "=[" + c.ToString()+ "] Index=" + c.Index + " Length=" + c.Length); } } //下一个匹配 m = m.NextMatch(); } }
/// <summary> /// Get the converted replacement from the cache or perform conversion and cache. /// </summary> /// <param name="regex"></param> /// <param name="replacement"></param> /// <returns></returns> internal static string ConvertReplacement(Regex/*!*/regex, string/*!*/replacement) { int[] group_numbers = regex.GetGroupNumbers(); int max_number = (group_numbers.Length > 0) ? group_numbers[group_numbers.Length - 1] : 0; return ConvertReplacement(max_number, replacement); }
static void Main(string[] args) { #region parse and check command line parameters if (args.Length < 2) { displayUsage(); return; } bool recursive = MyGlobalMethods.Contains(args, "-r"); bool regexp = MyGlobalMethods.Contains(args, "-x"); bool dirsToo = MyGlobalMethods.Contains(args, "-d"); bool notReal = MyGlobalMethods.Contains(args, "-t"); bool caseSensitive = MyGlobalMethods.Contains(args, "-s"); string inPattern = args[args.Length - 2]; string outPattern = args[args.Length - 1]; Regex inReg; RegexOptions regOpt = RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ECMAScript; if (!caseSensitive) { regOpt |= RegexOptions.IgnoreCase; } //RegExps if (regexp) { inReg = new Regex(inPattern, regOpt); if (inReg.GetGroupNumbers().Length <= 1) { Console.WriteLine("You have to use at least one group in your Regexp!"); return; } } //Wildcards //we escape all chars but the wildcard character '*' else { inReg = new Regex(Regex.Escape(inPattern).Replace(@"\*", "(.*)"), regOpt); } #endregion #region build regex pattern int i = 0; while (outPattern.Contains("*")) { i++; outPattern = MyGlobalMethods.ReplaceFirst(outPattern, "*", "\\" + i.ToString()); } #endregion var curDir = Directory.GetCurrentDirectory(); var matches = startRename(inReg, outPattern, curDir, recursive, dirsToo, notReal); if (matches == 0) { Console.WriteLine("Sorry, I couldn't find a file or directory matching '" + inReg.ToString() + "'"); Console.WriteLine("Remember that '^' is a escape character in DOS and you probably have to use '^^'."); } }