本文整理匯總了C#中System.Text.RegularExpressions.Regex.GetGroupNumbers方法的典型用法代碼示例。如果您正苦於以下問題:C# Regex.GetGroupNumbers方法的具體用法?C# Regex.GetGroupNumbers怎麽用?C# Regex.GetGroupNumbers使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Text.RegularExpressions.Regex
的用法示例。
在下文中一共展示了Regex.GetGroupNumbers方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: Rule
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));
}
示例2: UriPattern
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;
}
示例3: TrimMiddleProcessor
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)");
}
}
}
示例4: Column
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)");
}
}
}
示例5: UriPattern
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;
}
示例6: Main
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();
}
}
示例7: ScanForTokens
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());
}
示例8: Execute
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);
}
}
示例9: llHTTPRequest
//.........這裏部分代碼省略.........
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;
}
示例10: DgvColumnsCellEndEdit
/// <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.
}
}
}
}
示例11: ExtractSubexpressions
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;
}
示例12: Execute
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);
}
}
}
示例13: AsyncTest
/// <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)
//.........這裏部分代碼省略.........
示例14: llHTTPRequest
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;
}
示例15: Replace
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;
}
}