مشاركة عبر


نموذج كائن التعبير العادي

يصف هذا الموضوع طراز كائن المستخدم في التعامل مع إطار عمل.NET تعابير عادية. ويحتوي على الأقسام التالية:

  • مشغل التعبير العادي

  • الكائنات و مطابقة MatchCollection

  • مجموعة المجموعة

  • المجموعة الملتقطة

  • مجموعة الالتقاط

  • الالتقاط الفردي

مشغل التعبير العادي

يتم تمثيل مشغّل التعبير العادي في NET Framework. بالفئة Regex. مشغل التعبير النظامي المسؤولة عن تحليل و ترجمة تعبير عادي، و لتنفيذ العمليات مطابقة نقش التعبير العادي الذي يحتوي سلسلة إدخال. المشغل هو مكون مركزي في إطار عمل.NET العادي تعبير طراز الكائن.

يمكنك استخدام مشغل التعبيرات العادية بإحدى طريقتين:

  • بواسطة استدعاء وظائف ثابتة من Regexفئة. تتضمن معلمات الأسلوب سلسلة الإدخال ونمط التعبير العادي. ذاكرات التخزين المؤقت للمشغل التعبير العادي تعابير عادية والتي تستخدم في استدعاءات الأسلوب ثابتاً، حيث تقدم المتكررة استدعاء وظائف التعبير العادي الثابتة التي تستخدم نفس التعبير العادي أداء جيدا نسبيا.

  • بواسطة instantiating Regexكائن، بتمرير تعبير عادي إلى الدالة الإنشائية الفئة. في هذه الحالة، يصبح الكائن Regex غير قابل للتغيير (للقراءة فقط) ويمثل مشغّل تعبير عادي تم ربطه بدقة مع مشغل تعبير عادي وحيد. لأن استخدام تعبيرات عادية قبل Regexلا يتم تخزينها مؤقتاً مثيلات، لا يجب إنشاء مثيل Regexالكائن عدة مرة/مرات بنفس تعبير عادي.

يمكنك استدعاء الأساليب Regexالفئة إلى تنفيذ العمليات التالية:

  • تحديد ما إذا كانت سلسلة التلائمات نمط تعبير عادي.

  • تستخرج تطابق وحيد أو التطابق الأول.

  • استخراج كافة التطابقات.

  • استبدال سلسلة فرعية متطابقة.

  • تقسيم سلسلة وحيدة إلي صفيف من السلاسل.

يتم وصف هذه العمليات في الأقسام التالية.

مطابقة نقش تعبير عادي

Regex.IsMatchإرجاع أسلوب trueإذا كانت السلسلة التلائمات نقش، أو falseإذا أدى عدم. تستخدم الأسلوب IsMatch غالباً للتحقق من صحة سلسلة الإدخال. على سبيل المثال، تضمن التعليمة البرمجية التالية أن السلسلة تطابق رقم التأمين الاجتماعي صالح في الولايات المتحدة.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim values() As String = { "111-22-3333", "111-2-3333"}
      Dim pattern As String = "^\d{3}-\d{2}-\d{4}$"
      For Each value As String In values
         If Regex.IsMatch(value, pattern) Then
            Console.WriteLine("{0} is a valid SSN.", value)
         Else   
            Console.WriteLine("{0}: Invalid", value)
         End If   
      Next
   End Sub
End Module
' The example displays the following output:
'       111-22-3333 is a valid SSN.
'       111-2-3333: Invalid
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string[] values = { "111-22-3333", "111-2-3333"};
      string pattern = @"^\d{3}-\d{2}-\d{4}$";
      foreach (string value in values) {
         if (Regex.IsMatch(value, pattern))
            Console.WriteLine("{0} is a valid SSN.", value);
         else   
            Console.WriteLine("{0}: Invalid", value);
      }
   }
}
// The example displays the following output:
//       111-22-3333 is a valid SSN.
//       111-2-3333: Invalid

يتم تفسير نموذج التعبير العادي ^\d{3}-\d{2}-\d{4}$ كما هو موضح في الجدول التالي.

النمط

الوصف

^

تتطابق مع بداية سلسلة الإدخال.

\d{3}

تطابق ثلاثة الأرقام عشرية.

-

يتطابق مع واصلة.

\d{2}

تطابق رقمين عشريين.

-

يتطابق مع واصلة.

\d{4}

تتطابق أربعة أرقام عشرية.

$

مطابقة لنهاية سلسلة الإدخال.

استخراج مطابقة واحدة أو التطابق أول

تقوم الأسلوب Regex.Match بإرجاع الكائن Match الذي يحتوي على معلومات حول السلسلة الفرعية الأولي التي تطابق نمط التعبير العادي. إذا Match.Successخاصية بإرجاع true، تشير إلى التي التلائمات يتم العثور على، يمكنك استرداد المعلومات حول التلائمات عم اللاحقة بواسطة استدعاء Match.NextMatchالأسلوب. يمكن متابعة هذه استدعاءات الأسلوب حتى تقوم الخاصية Match.Success بإرجاع false. على سبيل المثال، تستخدم التعليمة البرمجية التالية الأسلوب Regex.Match(String, String) للعثور على التواجد الأول من كلمة مكررة في السلسلة. ثم تقوم باستدعاء الأسلوب Match.NextMatch للعثور على أي تكرارات إضافية. يختبر المثال Match.Successخاصية بعد كل استدعاء الأسلوب إلى لتحديد ما إذا كان نجاح المباراة الحالي وما إذا كانت المكالمة إلى Match.NextMatchيجب أن الأسلوب التالي.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "This is a a farm that that raises dairy cattle." 
      Dim pattern As String = "\b(\w+)\W+(\1)\b"
      Dim match As Match = Regex.Match(input, pattern)
      Do While match.Success
         Console.WriteLine("Duplicate '{0}' found at position {1}.", _ 
                           match.Groups(1).Value, match.Groups(2).Index)
         match = match.NextMatch()
      Loop                       
   End Sub
End Module
' The example displays the following output:
'       Duplicate 'a' found at position 10.
'       Duplicate 'that' found at position 22.
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "This is a a farm that that raises dairy cattle."; 
      string pattern = @"\b(\w+)\W+(\1)\b";
      Match match = Regex.Match(input, pattern);
      while (match.Success)
      {
         Console.WriteLine("Duplicate '{0}' found at position {1}.",  
                           match.Groups[1].Value, match.Groups[2].Index);
         match = match.NextMatch();
      }                       
   }
}
// The example displays the following output:
//       Duplicate 'a' found at position 10.
//       Duplicate 'that' found at position 22.

يتم تفسير نموذج التعبير العادي \b(\w+)\W+(\1)\b كما هو موضح في الجدول التالي.

النمط

الوصف

\b

تبدأ التطابق عند حدود كلمة.

(\w+)

تتوافق مع حرف أو أكثر لكلمة. هذه هي أول مجموعة الالتقاط.

\W+

تتوافق مع حرف أو أكثر لغير الكلمة.

(\1)

تطابق سلسلة الالتقاط الأولي. هذه هي مجموعة الالتقاط الثانية.

\b

إنهاء التطابق عند حدود الكلمة.

استخراج الجميع التطابقات

تقوم الأسلوب Regex.Matches بإرجاع الكائن MatchCollection الذي يحتوي على معلومات حول كافة التطابقات مع مشغل التعبيرات العادية التي تم العثور عليها في سلسلة الإدخال على سبيل المثال، قد يمكن كتابة المثال السابق لإجراء مكالمة Matchesالأسلوب بدلاً من Matchو NextMatchالأساليب.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "This is a a farm that that raises dairy cattle." 
      Dim pattern As String = "\b(\w+)\W+(\1)\b"
      For Each match As Match In Regex.Matches(input, pattern)
         Console.WriteLine("Duplicate '{0}' found at position {1}.", _ 
                           match.Groups(1).Value, match.Groups(2).Index)
      Next                       
   End Sub
End Module
' The example displays the following output:
'       Duplicate 'a' found at position 10.
'       Duplicate 'that' found at position 22.
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "This is a a farm that that raises dairy cattle."; 
      string pattern = @"\b(\w+)\W+(\1)\b";
      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine("Duplicate '{0}' found at position {1}.",  
                           match.Groups[1].Value, match.Groups[2].Index);
   }
}
// The example displays the following output:
//       Duplicate 'a' found at position 10.
//       Duplicate 'that' found at position 22.

استبدال سلسلة فرعية تطابق

يقوم الأسلوب Regex.Replace باستبدال كل سلسلة فرعية تطابق نمط التعبير العادي بالسلسلة المحددة أو نقش التعبير العادي وإرجاع سلسلة الإدخال بأكملها مع الاستبدالات. ل مثال، إضافة التعليمة البرمجية التالية الولايات المتحدة الرمز العملة قبل رقم عشري في سلسلة.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b\d+\.\d{2}\b"
      Dim replacement As String = "$$$&" 
      Dim input As String = "Total Cost: 103.64"
      Console.WriteLine(Regex.Replace(input, pattern, replacement))     
   End Sub
End Module
' The example displays the following output:
'       Total Cost: $103.64
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b\d+\.\d{2}\b";
      string replacement = "$$$&"; 
      string input = "Total Cost: 103.64";
      Console.WriteLine(Regex.Replace(input, pattern, replacement));     
   }
}
// The example displays the following output:
//       Total Cost: $103.64

تعبير عادي النقش \b\d+\. \d{2}\b is interpreted as shown in the following table.

النمط

الوصف

\b

تبدأ التطابق عند حدود كلمة.

\d+

مطابقة واحد او اكثر من الأرقام العشرية.

\.

يطابق نقطة (.).

\d{2}

تطابق رقمين عشريين.

\b

إنهاء التطابق عند حدود الكلمة.

يتم تفسير النقش المستبدل $$$& كما هو موضح في الجدول التالية.

النمط

سلسلة الاستبدال

$$

حرف علامة الدولار ($).

$&

السلسلة الفرعية المطابقة بأكملها.

تقسيم سلسلة مفرد إلى صفيفة سلاسل

تقسم الأسلوب Regex.Splitسلسلة الإدخال في المواضع المعرّفة من قِبل تعبير عادي مطابق. على سبيل المثال، تضع التعليمة البرمجية التالية العناصر في قائمة ذات تعداد رقمي في سلسلة صفيف.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "1. Eggs 2. Bread 3. Milk 4. Coffee 5. Tea"
      Dim pattern As String = "\b\d{1,2}\.\s"
      For Each item As String In Regex.Split(input, pattern)
         If Not String.IsNullOrEmpty(item) Then
            Console.WriteLine(item)
         End If
      Next      
   End Sub
End Module
' The example displays the following output:
'       Eggs
'       Bread
'       Milk
'       Coffee
'       Tea
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "1. Eggs 2. Bread 3. Milk 4. Coffee 5. Tea";
      string pattern = @"\b\d{1,2}\.\s";
      foreach (string item in Regex.Split(input, pattern))
      {
         if (! String.IsNullOrEmpty(item))
            Console.WriteLine(item);
      }      
   }
}
// The example displays the following output:
//       Eggs
//       Bread
//       Milk
//       Coffee
//       Tea

تعبير عادي النقش \b\d{1,2}\. \s is interpreted as shown in the following table.

النمط

الوصف

\b

تبدأ التطابق عند حدود كلمة.

\d{1,2}

مطابقة واحد او اكثر من الأرقام العشرية.

\.

يطابق نقطة (.).

\s

تطابق حرف المسافة.

الكائنات و مطابقة MatchCollection

تُرجع أساليب Regex كائنين يعدان جزءًا من نموذج كائن التعبير العادي: الكائن MatchCollection، والكائن Match.

المجموعة المطابقة

Regex.Matchesإرجاع الأسلوب MatchCollectionالكائن الذي يحتوي على Matchالكائنات التي تمثل الجميع التطابقات التي العادية تعبير العثور على مشغل، بالترتيب فيه حدوثها في سلسلة إدخال. في حالة عدم وجود تطابقات يقوم الأسلوب بإرجاع الكائن MatchCollection بدون أعضاء. MatchCollection.Itemالخاصية يتيح لك الوصول إلى الأعضاء مفردة مجموعة حسب الفهرس، من صفر إلى أصغر من من القيمة واحدة MatchCollection.Countالخاصية. Itemهو مفهرس (في C#) في المجموعة والخاصية الافتراضية (ب Vهوual أساسي).

افتراضياً، يكون للاستدعاء إلى Regex.Matchesيستخدم أسلوب تقييم البطيئة إلى نشر MatchCollectionالكائن. الوصول إلى الخصائص التي تتطلب مجموعة populated بشكل كامل، مثل كـ MatchCollection.Countو MatchCollection.Itemقد تتضمن الخصائص، جزاء الأداء. ونتيجة لذلك، فإننا نوصي بالوصول إلى مجموعة باستخدام IEnumeratorالكائن الذي هو التي يتم إرجاعها بواسطة MatchCollection.GetEnumeratorالأسلوب. Individual languages provide constructs, such as For Each in Visual Basic and foreach in C#, that wrap the collection's IEnumerator interface.

يستخدم المثال التالي Regex.Matches(String)أسلوب إلى ملء MatchCollectionالكائن مع الجميع التطابقات الموجودة على سلسلة إدخال. تعداد المثال مجموعة النسخ التطابقات إلى صفيفة سلسلة ويسجل موضع الحرف في صفيفة صحيحاً.

Imports System.Collections.Generic
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
       Dim matches As MatchCollection
       Dim results As New List(Of String)
       Dim matchposition As New List(Of Integer)

       ' Create a new Regex object and define the regular expression.
       Dim r As New Regex("abc")
       ' Use the Matches method to find all matches in the input string.
       matches = r.Matches("123abc4abcd")
       ' Enumerate the collection to retrieve all matches and positions.
       For Each match As Match In matches
          ' Add the match string to the string array.
           results.Add(match.Value)
           ' Record the character position where the match was found.
           matchposition.Add(match.Index)
       Next
       ' List the results.
       For ctr As Integer = 0 To results.Count - 1
         Console.WriteLine("'{0}' found at position {1}.", _
                           results(ctr), matchposition(ctr))  
       Next
   End Sub
End Module
' The example displays the following output:
'       'abc' found at position 3.
'       'abc' found at position 7.
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
       MatchCollection matches;
       List<string> results = new List<string>();
       List<int> matchposition = new List<int>();

       // Create a new Regex object and define the regular expression.
       Regex r = new Regex("abc");
       // Use the Matches method to find all matches in the input string.
       matches = r.Matches("123abc4abcd");
       // Enumerate the collection to retrieve all matches and positions.
       foreach (Match match in matches)
       {
          // Add the match string to the string array.
           results.Add(match.Value);
           // Record the character position where the match was found.
           matchposition.Add(match.Index);
       }
       // List the results.
       for (int ctr = 0; ctr < results.Count; ctr++)
         Console.WriteLine("'{0}' found at position {1}.", 
                           results[ctr], matchposition[ctr]);  
   }
}
// The example displays the following output:
//       'abc' found at position 3.
//       'abc' found at position 7.

التطابق

Matchفئة يمثل نتيجة تطابق تعبير عادي واحد. يمكنك الوصول إلى Matchالكائنات في الثاني طرق:

  • ذلك بواسطة استردادها من MatchCollectionالكائن الذي هو التي يتم إرجاعها بواسطة Regex.Matchesالأسلوب. إلى استرداد الفردية Matchالكائنات، قم بيكرر المجموعة باستخدام foreach(في C#) أو For Each...Next (في Visual أساسى) إنشاء أو استخدام MatchCollection.Itemالخاصية إلى استرداد معين Matchالكائن حسب الفهرس أو حسب الاسم. ويمكنك أيضًا استرداد الكائنات الفردية Match من المجموعة بواسطة تكرار المجموعة حسب الفهرس، من الصفر إلي عدد كائنات المجموعة مطروحاً منه واحد. على الرغم من ذلك، هذا أسلوب لا يستفيد من تقييم البطيئة، لأن يصل إلى MatchCollection.Countخاصية.

    يقوم المثال التالي باسترداد الكائنات الفردية Match من الكائن MatchCollection بواسطة تكرار المجموعة باستخدام الإنشاء foreach أو For Each...Next. التعبيرات العادية ببساطة تطابق السلسلة "أ ب ج" في سلسلة الإدخال.

    Imports System.Text.RegularExpressions
    
    Module Example
       Public Sub Main()
          Dim pattern As String = "abc"
          Dim input As String = "abc123abc456abc789"
          For Each match As Match In Regex.Matches(input, pattern)
             Console.WriteLine("{0} found at position {1}.", _
                               match.Value, match.Index)
          Next                     
       End Sub
    End Module
    ' The example displays the following output:
    '       abc found at position 0.
    '       abc found at position 6.
    '       abc found at position 12.
    
    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          string pattern = "abc";
          string input = "abc123abc456abc789";
          foreach (Match match in Regex.Matches(input, pattern))
             Console.WriteLine("{0} found at position {1}.", 
                               match.Value, match.Index);
       }
    }
    // The example displays the following output:
    //       abc found at position 0.
    //       abc found at position 6.
    //       abc found at position 12.
    
  • عن طريق استدعاء الأسلوب Regex.Match، التي تقوم بإرجاع الكائن Match الذي يمثل التطابق الأول في سلسلة أو جزء من سلسلة. يمكنك تحديد ما إذا كان مطابقة يتم العثور على طريق استرداد القيمة Match.Successخاصية. لاسترداد Matchالكائنات التي تمثل لاحقة التلائمات، اتصل Match.NextMatchالأسلوب بشكل متكرر، حتى Successخاصية يتم إرجاع Matchالكائن هو false.

    يستخدم المثال التالي في Regex.Match(String, String)و Match.NextMatchوظائف إلى يطابق السلسلة "ا بج" في سلسلة إدخال.

    Imports System.Text.RegularExpressions
    
    Module Example
       Public Sub Main()
          Dim pattern As String = "abc"
          Dim input As String = "abc123abc456abc789"
          Dim match As Match = Regex.Match(input, pattern)
          Do While match.Success
             Console.WriteLine("{0} found at position {1}.", _
                               match.Value, match.Index)
             match = match.NextMatch()                  
          Loop                     
       End Sub
    End Module
    ' The example displays the following output:
    '       abc found at position 0.
    '       abc found at position 6.
    '       abc found at position 12.
    
    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          string pattern = "abc";
          string input = "abc123abc456abc789";
          Match match = Regex.Match(input, pattern);
          while (match.Success)
          {
             Console.WriteLine("{0} found at position {1}.", 
                               match.Value, match.Index);
             match = match.NextMatch();                  
          }                     
       }
    }
    // The example displays the following output:
    //       abc found at position 0.
    //       abc found at position 6.
    //       abc found at position 12.
    

خاصيتين من Matchفئة إعادة تجميع الكائنات:

  • تقوم الخاصية Match.Groups بإرجاع الكائن GroupCollection الذي يحتوي على معلومات حول السلاسل الفرعية التي تطابق مجموعات الالتقاط في نمط التعبير العادي.

  • Group.Capturesإرجاع خاصية CaptureCollectionالكائن الذي هو للاستخدام المحدود. لم يتم تعبئة المجموعة ل Matchكائن له Successخاصية false. وإلا يحتوي على مفرد Captureكائن يحتوي على نفس المعلومات ك Matchكائن.

لمزيد من المعلومات حول هذه الكائنات راجع المقاطع مجموعة المجموعة و مجموعة الالتقاط لاحقًا في هذا الموضوع.

توفر خاصيتين إضافيتين للفئة Match معلومات حول التطابق. تقوم الخاصية Match.Value بإرجاع السلسلة الفرعية في سلسلة الإدخال التي تتطابق مع نمط التعبير العادي. تقوم الخاصية Match.Index بإرجاع موضع بدء الذي يستند علي القيمة صفر للسلسلة المطابقة في سلسلة الإدخال.

Matchالفئة يتوفر اثنين نقش-المطابقة للأساليب:

  • Match.NextMatchالعثور على أسلوب المطابقة بعد المباراة يمثله الحالي Matchالكائن، و بإرجاع Matchالكائن الذي يمثل ذلك مطابقة.

  • ينفذ الأسلوب Match.Result عملية استبدال محددة على السلسلة المطابقة ويقوم بإرجاع النتيجة.

يستخدم المثال التالي Match.Resultأسلوب إلى prepend الرمز $ ومسافة قبل كل رقم يحتوي على عمودين الأرقام كسرى.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b\d+(,\d{3})*\.\d{2}\b"
      Dim input As String = "16.32" + vbCrLf + "194.03" + vbCrLf + "1,903,672.08" 

      For Each match As Match In Regex.Matches(input, pattern)
         Console.WriteLine(match.Result("$$ $&"))
      Next
   End Sub
End Module
' The example displays the following output:
'       $ 16.32
'       $ 194.03
'       $ 1,903,672.08
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b\d+(,\d{3})*\.\d{2}\b";
      string input = "16.32\n194.03\n1,903,672.08"; 

      foreach (Match match in Regex.Matches(input, pattern))
         Console.WriteLine(match.Result("$$ $&"));
   }
}
// The example displays the following output:
//       $ 16.32
//       $ 194.03
//       $ 1,903,672.08

تعبير عادي النقش \b\d+(,\d{3})*\. \d{2}\b is defined as shown in the following table.

النمط

الوصف

\b

تبدأ التطابق عند حدود كلمة.

\d+

مطابقة واحد او اكثر من الأرقام العشرية.

(,\d{3})*

مطابقة صفر أو أكثر تواجدات فاصلة يتبعها ثلاثة صواب الأرقام.

\.

تطابق الأحرف الفاصلة العشرية.

\d{2}

تطابق رقمين عشريين.

\b

إنهاء التطابق عند حدود الكلمة.

النقش الاستبدال $$ $&يشير إلى السلسلة الفرعية متطابقة يجب استبداله برمز الدولار ($) ( $$نقش)، المساحة، و القيمة المطابقة ( $&نقش).

العودة إلى الأعلى

مجموعة المجموعة

تقوم الخاصية Match.Groups بإرجاع الكائن GroupCollection الذي يحتوي على الكائنات Group التي تمثل المجموعات الملتقطة في مطابقة واحدة. الكائن الأول Group في المجموعة (عند الفهرس 0) يمثل التطابق بالكامل. يمثل كل كائن يتبع نتائج مجموعة الالتقاط واحدة.

يمكنك استرداد الفردية Groupعلى الكائنات في مجموعة باستخدام GroupCollection.Itemخاصية. يمكنك استرداد مجموعات غير المسماة بواسطة الموضع الترتيبي الخاصة بهم في مجموعة، واسترداد المسمى مجموعات حسب الاسم أو حسب الموضع الترتيبي. اللقطات غير المسماه تظهر أولاً في المجموعة ويتم فهرستها من اليسار إلى اليمين في الترتيب الذي تظهر به في نمط التعبير العادي. يتم تمت الفهرسة الأسر المسماة بعد الأسر غير مسمى، اليسار لليمين بالترتيب الذي تظهر فيه في النقش تعبير عادي.

الخاصية GroupCollection.Item هي المفهرس للمجموعة في C# والخاصية الافتراضية لكائن المجموعة في Visual Basic. وهذا يعني أن الكائنات الفردية Group يمكن الوصول إليها بواسطة الفهرس (أو حسب الاسم في حالة المجموعات المسماة) كما يلي:

Dim group As Group = match.Groups(ctr)         
Group group = match.Groups[ctr];         

يعرف المثال التالي تعبير عادي يستخدم إنشاء المجموعات لالتقاط الشهر واليوم والسنة من تاريخ ما.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b(\w+)\s(\d{1,2}),\s(\d{4})\b"
      Dim input As String = "Born: July 28, 1989"
      Dim match As Match = Regex.Match(input, pattern)
      If match.Success Then
         For ctr As Integer = 0 To match.Groups.Count - 1
            Console.WriteLine("Group {0}: {1}", ctr, match.Groups(ctr).Value)
         Next      
      End If   
   End Sub
End Module
' The example displays the following output:
'       Group 0: July 28, 1989
'       Group 1: July
'       Group 2: 28
'       Group 3: 1989
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b(\w+)\s(\d{1,2}),\s(\d{4})\b";
      string input = "Born: July 28, 1989";
      Match match = Regex.Match(input, pattern);
      if (match.Success)
         for (int ctr = 0; ctr <  match.Groups.Count; ctr++)
            Console.WriteLine("Group {0}: {1}", ctr, match.Groups[ctr].Value);
    }
}
// The example displays the following output:
//       Group 0: July 28, 1989
//       Group 1: July
//       Group 2: 28
//       Group 3: 1989

يتم تعريف نمط التعبير العادي \b(\w+)\s(\d{1,2}),\s(\d{4})\b كما هو موضح في الجدول التالية.

النمط

الوصف

\b

تبدأ التطابق عند حدود كلمة.

(\w+)

تتوافق مع حرف أو أكثر لكلمة. هذه هي أول مجموعة الالتقاط.

\s

تطابق حرف المسافة.

(\d{1,2})

مطابقة واحد او اكثر من الأرقام العشرية. هذه هي مجموعة الالتقاط الثانية.

,

يطابق فاصلة.

\s

تطابق حرف المسافة.

(\d{4})

تتطابق أربعة أرقام عشرية. هذه هي مجموعة الالتقاط الثالثة.

\b

إنهاء التطابق عند حدود الكلمة.

العودة إلى الأعلى

المجموعة الملتقطة

تمثل الفئة Group نتيجة مجموعة التقاط وحيد. تجميع الكائنات التي تمثل المجموعات الالتقاط في تعبير عادي يتم إرجاعها بواسطة Itemخاصية GroupCollectionكائن تم إرجاعه بواسطة Match.Groupsالخاصية. الخاصية Item هي المفهرس (في C#) و الخاصية الافتراضية للفئة (في Visual Basic) Group. You can also retrieve individual members by iterating the collection using the foreach or For Each construct. على سبيل المثال، راجع المقطع السابق.

يستخدم المثال التالي بنيات تجميع المتداخلة لالتقاط سلاسل فرعية ضمن مجموعات. تعبير عادي نقش (a(b))cيطابق السلسلة "ا بج". يقوم بتعيين السلسلة الفرعية "ab" إلى أول التقاط مجموعة وسلسلة فرعية "b" للمجموعة ثانية الالتقاط.

 Dim matchposition As New List(Of Integer)
 Dim results As New List(Of String)
 ' Define substrings abc, ab, b.
 Dim r As New Regex("(a(b))c") 
 Dim m As Match = r.Match("abdabc")
 Dim i As Integer = 0
 While Not (m.Groups(i).Value = "")    
    ' Add groups to string array.
    results.Add(m.Groups(i).Value)     
    ' Record character position. 
    matchposition.Add(m.Groups(i).Index) 
     i += 1
 End While

 ' Display the capture groups.
 For ctr As Integer = 0 to results.Count - 1
    Console.WriteLine("{0} at position {1}", _ 
                      results(ctr), matchposition(ctr))
 Next                     
' The example displays the following output:
'       abc at position 3
'       ab at position 3
'       b at position 4
List<int> matchposition = new List<int>();
List<string> results = new List<string>();
// Define substrings abc, ab, b.
Regex r = new Regex("(a(b))c"); 
Match m = r.Match("abdabc");
for (int i = 0; m.Groups[i].Value != ""; i++) 
{
   // Add groups to string array.
   results.Add(m.Groups[i].Value); 
   // Record character position.
   matchposition.Add(m.Groups[i].Index); 
}

// Display the capture groups.
for (int ctr = 0; ctr < results.Count; ctr++)
   Console.WriteLine("{0} at position {1}", 
                     results[ctr], matchposition[ctr]);
// The example displays the following output:
//       abc at position 3
//       ab at position 3
//       b at position 4

يستخدم المثال التالي بنيات تجميع المسمى إلى التقاط سلاسل فرعية من سلسلة أحرف التي تحتوي على بيانات بتنسيق "DATANAME:القيمة"، الذي ينقسم تعبير عادي في النقطتين (:).

Dim r As New Regex("^(?<name>\w+):(?<value>\w+)")
Dim m As Match = r.Match("Section1:119900")
Console.WriteLine(m.Groups("name").Value)
Console.WriteLine(m.Groups("value").Value)
' The example displays the following output:
'       Section1
'       119900
Regex r = new Regex("^(?<name>\\w+):(?<value>\\w+)");
Match m = r.Match("Section1:119900");
Console.WriteLine(m.Groups["name"].Value);
Console.WriteLine(m.Groups["value"].Value);
// The example displays the following output:
//       Section1
//       119900

يتم تعريف نمط التعبير العادي ^(?<name>\w+):(?<value>\w+) كما هو موضح في الجدول التالية.

النمط

الوصف

^

تبدأ التطابق عند بداية سلسلة الإدخال.

(?<name>\w+)

تتوافق مع حرف أو أكثر لكلمة. اسم مجموعة الالتقاط هذه هو name.

:

مطابقة نقطتين.

(?<value>\w+)

تتوافق مع حرف أو أكثر لكلمة. اسم مجموعة الالتقاط هذه هو value.

الخصائص Groupفئة بتوفير المعلومات تم التقاطها مجموعة: تحتوي الخاصية Group.Valueعلى السلسلة الفرعية التي تم التقاطها، وتشير الخاصية Group.Index إلى موضع البداية للمجموعة التي تم التقاطها في نص الإدخال، وتحتوي الخاصية Group.Length على طول النص الملتقط، وتشير الخاصية Group.Success إلى ما إذا كانت السلسلة الفرعية مطابقة للنقش المعرّف بواسطة مجموعة الالتقاط.

تطبيق quantifiers إلى مجموعة (للحصول على مزيد من المعلومات، راجع محددو الكمية) بتعديل العلاقة ليلتقط واحدة في يلتقط مجموعة بطريقتين:

  • إذا كانت *أو *?quantifier (الذي يحدد التلائمات صفر أو أكثر) هو تطبيق مجموعة، مجموعة الالتقاط قد لا تكون التلائمات في سلسلة إدخال. عندما لا يوجد نص ملتقط، يتم تعيين خصائص الكائن Group كما هو موضح في الجدول التالية.

    مجموعة الخاصية

    Value

    Success

    false

    Value

    String.Empty

    Length

    0

    يوفر المثال التالي توضيح. في نمط التعبير العادي aaa(bbb)*ccc ، يمكن أن تتطابق أول مجموعة التقاط (السلسلة الفرعية "bbb") صفر مرة أو أكثر من مرة. بسبب تطابق سلسلة الإدخال "aaaccc" للنمط، لا تحتوي مجموعة الالتقاط علي مطابقة.

    Imports System.Text.RegularExpressions
    
    Module Example
       Public Sub Main()
          Dim pattern As String = "aaa(bbb)*ccc"
          Dim input As String = "aaaccc"
          Dim match As Match = Regex.Match(input, pattern)
          Console.WriteLine("Match value: {0}", match.Value)
          If match.Groups(1).Success Then
             Console.WriteLine("Group 1 value: {0}", match.Groups(1).Value)
          Else
             Console.WriteLine("The first capturing group has no match.")
         End If   
       End Sub
    End Module
    ' The example displays the following output:
    '       Match value: aaaccc
    '       The first capturing group has no match.
    
    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          string pattern = "aaa(bbb)*ccc";
          string input = "aaaccc";
          Match match = Regex.Match(input, pattern);
          Console.WriteLine("Match value: {0}", match.Value);
          if (match.Groups[1].Success)
             Console.WriteLine("Group 1 value: {0}", match.Groups[1].Value);
          else
             Console.WriteLine("The first capturing group has no match.");
       }
    }
    // The example displays the following output:
    //       Match value: aaaccc
    //       The first capturing group has no match.
    
  • يمكنك مطابقة quantifiers التواجدات المتعددة لنمط التي هو المعرفة من قبل مجموعة الالتقاط. في هذه الحالة، Valueو Lengthخصائص Groupالكائن يحتوي على معلومات فقط حول أخير التقاط سلسلة فرعية. على سبيل المثال، يطابق التعبير العادي التالي جملة واحدة تنتهي في فترة ما. فهو يستخدم الثاني بنيات تجميع: الأولى بالتقاط كلمات فردية بالإضافة إلى مسافة بيضاء حرف; الثاني بالتقاط كلمات فردية. كما يظهر الإخراج من المثال، على الرغم من أن تعبير عادي بنجاح في التقاط جملة بأكمله، بالتقاط الثاني مجموعة يلتقط الكلمة الأخيرة فقط.

    Imports System.Text.RegularExpressions
    
    Module Example
       Public Sub Main()
          Dim pattern As String = "\b((\w+)\s?)+\."
          Dim input As String = "This is a sentence. This is another sentence."
          Dim match As Match = Regex.Match(input, pattern)
          If match.Success Then
             Console.WriteLine("Match: " + match.Value)
             Console.WriteLine("Group 2: " + match.Groups(2).Value)
          End If   
       End Sub
    End Module
    ' The example displays the following output:
    '       Match: This is a sentence.
    '       Group 2: sentence
    
    using System;
    using System.Text.RegularExpressions;
    
    public class Example
    {
       public static void Main()
       {
          string pattern = @"\b((\w+)\s?)+\.";
          string input = "This is a sentence. This is another sentence.";
          Match match = Regex.Match(input, pattern);
          if (match.Success)
          {
             Console.WriteLine("Match: " + match.Value);
             Console.WriteLine("Group 2: " + match.Groups[2].Value);
          }   
       }
    }
    // The example displays the following output:
    //       Match: This is a sentence.
    //       Group 2: sentence
    

العودة إلى الأعلى

مجموعة الالتقاط

يحتوي الكائن Group على معلومات فقط حول آخر التقاط. على الرغم من ذلك، قام التعيين كاملة من الأسر التعيين الالتقاط هو ستبقى متوفرة من CaptureCollectionالكائن الذي هو التي يتم إرجاعها بواسطة Group.Capturesخاصية. كل عضو في المجموعة هو Captureالكائن الذي يمثل بتلك المجموعة اليلتقط، بالترتيب الذي تم يلتقط لقطة (ولذلك، بالترتيب الذي تم مطابقة السلاسل التي تم يلتقطها من اليسار إلى الأيمن في سلسلة إدخال). يمكنك استرداد الفردية Captureالكائنات من المجموعة بإحدى طريقتين:

  • بواسطة التكرار خلال المجموعة باستخدام إنشاء مثل foreach (في#C )أو For Each (in Visual Basic).

  • باستخدام الخاصية CaptureCollection.Item لاسترداد كائن محدد بواسطة الفهرس. الخاصية Item هي الخاصية الافتراضية للكائن CaptureCollection (في Visual Basic) أو المفهرس (في C#).

إذا quantifier هو لن يطبق على مجموعة الالتقاط، CaptureCollectionيحتوي الكائن على واحدة Captureالكائن الذي هو القليل من الاهتمام، لأنه يوفر معلومات حول المباراة نفسها كبه Groupالكائن. إذا quantifier هو المطبق على مجموعة الالتقاط، CaptureCollectionيحتوي الكائن على الجميع الأسر التي قام بها مجموعة الالتقاط، ويمثل آخر عضو في مجموعة الالتقاط نفسها Groupالكائن.

على سبيل المثال، إذا كنت تستخدم نمط التعبير العادي ((a(b))c)+ (حيث محدد الكمية + تعيّن واحد من التطابقات أو أكثر) لالتقاط يطابق من السلسلة "abcabcabc"، فسيحتوي الكائن CaptureCollection لكل كائن Groupعلى ثلاثة أعضاء.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "((a(b))c)+"
      Dim input As STring = "abcabcabc"

      Dim match As Match = Regex.Match(input, pattern)
      If match.Success Then
         Console.WriteLine("Match: '{0}' at position {1}", _ 
                           match.Value, match.Index)
         Dim groups As GroupCollection = match.Groups
         For ctr As Integer = 0 To groups.Count - 1
            Console.WriteLine("   Group {0}: '{1}' at position {2}", _
                              ctr, groups(ctr).Value, groups(ctr).Index)
            Dim captures As CaptureCollection = groups(ctr).Captures
            For ctr2 As Integer = 0 To captures.Count - 1
               Console.WriteLine("      Capture {0}: '{1}' at position {2}", _
                                 ctr2, captures(ctr2).Value, captures(ctr2).Index)
            Next
         Next
      End If
   End Sub
End Module
' The example dosplays the following output:
'       Match: 'abcabcabc' at position 0
'          Group 0: 'abcabcabc' at position 0
'             Capture 0: 'abcabcabc' at position 0
'          Group 1: 'abc' at position 6
'             Capture 0: 'abc' at position 0
'             Capture 1: 'abc' at position 3
'             Capture 2: 'abc' at position 6
'          Group 2: 'ab' at position 6
'             Capture 0: 'ab' at position 0
'             Capture 1: 'ab' at position 3
'             Capture 2: 'ab' at position 6
'          Group 3: 'b' at position 7
'             Capture 0: 'b' at position 1
'             Capture 1: 'b' at position 4
'             Capture 2: 'b' at position 7
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = "((a(b))c)+";
      string input = "abcabcabc";

      Match match = Regex.Match(input, pattern);
      if (match.Success)
      {
         Console.WriteLine("Match: '{0}' at position {1}",  
                           match.Value, match.Index);
         GroupCollection groups = match.Groups;
         for (int ctr = 0; ctr < groups.Count; ctr++) {
            Console.WriteLine("   Group {0}: '{1}' at position {2}", 
                              ctr, groups[ctr].Value, groups[ctr].Index);
            CaptureCollection captures = groups[ctr].Captures;
            for (int ctr2 = 0; ctr2 < captures.Count; ctr2++) {
               Console.WriteLine("      Capture {0}: '{1}' at position {2}", 
                                 ctr2, captures[ctr2].Value, captures[ctr2].Index);
            }                     
         }
      }
   }
}
// The example displays the following output:
//       Match: 'abcabcabc' at position 0
//          Group 0: 'abcabcabc' at position 0
//             Capture 0: 'abcabcabc' at position 0
//          Group 1: 'abc' at position 6
//             Capture 0: 'abc' at position 0
//             Capture 1: 'abc' at position 3
//             Capture 2: 'abc' at position 6
//          Group 2: 'ab' at position 6
//             Capture 0: 'ab' at position 0
//             Capture 1: 'ab' at position 3
//             Capture 2: 'ab' at position 6
//          Group 3: 'b' at position 7
//             Capture 0: 'b' at position 1
//             Capture 1: 'b' at position 4
//             Capture 2: 'b' at position 7

يستخدم المثال التالي التعبير العادي (Abc)+ للعثور علي واحد أو اكثر من التشغيلات المتتالية للسلسلة "ABC" في السلسلة "XYZAbcAbcAbcXYZAbcAb". يوضح المثال استخدام الخاصية Group.Captures لإرجاع عدة مجموعات من السلاسل الفرعية الملتقطة.

Dim counter As Integer
Dim m As Match
Dim cc As CaptureCollection
Dim gc As GroupCollection

' Look for groupings of "Abc".
Dim r As New Regex("(Abc)+") 
' Define the string to search.
m = r.Match("XYZAbcAbcAbcXYZAbcAb")
gc = m.Groups

' Display the number of groups.
Console.WriteLine("Captured groups = " & gc.Count.ToString())

' Loop through each group.
Dim i, ii As Integer
For i = 0 To gc.Count - 1
    cc = gc(i).Captures
    counter = cc.Count

    ' Display the number of captures in this group.
    Console.WriteLine("Captures count = " & counter.ToString())

    ' Loop through each capture in the group.            
    For ii = 0 To counter - 1
        ' Display the capture and its position.
        Console.WriteLine(cc(ii).ToString() _
            & "   Starts at character " & cc(ii).Index.ToString())
    Next ii
Next i
' The example displays the following output:
'       Captured groups = 2
'       Captures count = 1
'       AbcAbcAbc   Starts at character 3
'       Captures count = 3
'       Abc   Starts at character 3
'       Abc   Starts at character 6
'       Abc   Starts at character 9  
   int counter;
   Match m;
   CaptureCollection cc;
   GroupCollection gc;

   // Look for groupings of "Abc".
   Regex r = new Regex("(Abc)+"); 
   // Define the string to search.
   m = r.Match("XYZAbcAbcAbcXYZAbcAb"); 
   gc = m.Groups;

   // Display the number of groups.
   Console.WriteLine("Captured groups = " + gc.Count.ToString());

   // Loop through each group.
   for (int i=0; i < gc.Count; i++) 
   {
      cc = gc[i].Captures;
      counter = cc.Count;

      // Display the number of captures in this group.
      Console.WriteLine("Captures count = " + counter.ToString());

      // Loop through each capture in the group.
      for (int ii = 0; ii < counter; ii++) 
      {
         // Display the capture and its position.
         Console.WriteLine(cc[ii] + "   Starts at character " + 
              cc[ii].Index);
      }
   }
}
// The example displays the following output:
//       Captured groups = 2
//       Captures count = 1
//       AbcAbcAbc   Starts at character 3
//       Captures count = 3
//       Abc   Starts at character 3
//       Abc   Starts at character 6
//       Abc   Starts at character 9  

العودة إلى الأعلى

الالتقاط الفردي

تحتوي الفئة Capture على النتائج من التقاط وحيد للتعبير الفرعي. وتحتوي الخاصية Capture.Value على النص المتطابق و تشير الخاصية Capture.Indexإلى موضع البدء المستند إلي الصفر في سلسلة الإدخال التي تبدأ السلسلة الفرعية المتطابقة عندها.

يحلل المثال التالي سلسلة إدخال لدرجة الحرارة لمدينة محددة. وتستخدم الفاصلة (",") لفصل المدينة و الحرارة الخاصة بها وتستخدم الفاصلة المنقوطة (";") لفصل بيانات كل مدينة. تمثل سلسلة الإدخال بالكامل تطابق وحيد. في تعبير عادي نقش ((\w+(\s\w+)*),(\d+);)+، أي هو تستخدم لتحليل السلسلة، اسم المدينة هو المعينة للمجموعة ثانية الالتقاط، ودرجة الحرارة في هو المعينة إلى الرابع مجموعة الالتقاط.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "Miami,78;Chicago,62;New York,67;San Francisco,59;Seattle,58;" 
      Dim pattern As String = "((\w+(\s\w+)*),(\d+);)+"
      Dim match As Match = Regex.Match(input, pattern)
      If match.Success Then
         Console.WriteLine("Current temperatures:")
         For ctr As Integer = 0 To match.Groups(2).Captures.Count - 1
            Console.WriteLine("{0,-20} {1,3}", match.Groups(2).Captures(ctr).Value, _
                              match.Groups(4).Captures(ctr).Value)
         Next
      End If
   End Sub
End Module
' The example displays the following output:
'       Current temperatures:
'       Miami                 78
'       Chicago               62
'       New York              67
'       San Francisco         59
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "Miami,78;Chicago,62;New York,67;San Francisco,59;Seattle,58;"; 
      string pattern = @"((\w+(\s\w+)*),(\d+);)+";
      Match match = Regex.Match(input, pattern);
      if (match.Success)
      {
         Console.WriteLine("Current temperatures:");
         for (int ctr = 0; ctr < match.Groups[2].Captures.Count; ctr++)
            Console.WriteLine("{0,-20} {1,3}", match.Groups[2].Captures[ctr].Value, 
                              match.Groups[4].Captures[ctr].Value);
      }
   }
}
// The example displays the following output:
//       Current temperatures:
//       Miami                 78
//       Chicago               62
//       New York              67
//       San Francisco         59

يتم تعريف التعبير العادي كما هو موضح في الجدول التالي.

النمط

الوصف

\w+

تتوافق مع حرف أو أكثر لكلمة.

(\s\w+)*

مطابقة تواجد صفر أو أكثر لحرف المسافة البيضاء متبوعاً بواحد أو أكثر الكلمة الأحرف. هذا نقش يطابق أسماء multi-الكلمة المدينة. هذه هي مجموعة الالتقاط الثالثة.

(\w+(\s\w+)*)

مطابقة أحرف كلمة أو أكثر متبوعة بتواجد صفر أو أكثر لحرف المسافة البيضاء و حرف كلمة أو أكثر. هذه هي مجموعة الالتقاط الثانية.

,

يطابق فاصلة.

(\d+)

مطابقة واحد او اكثر من الأرقام. هذه هي مجموعة الالتقاط الرابعة.

;

يتطابق مع فاصلة منقوطة.

((\w+(\s\w+)*),(\d+);)+

تطابق نمط كلمة متبوعة بأية كلمات إضافية متبوعة بفاصلة أو رقم أو أكثر أو فاصلة منقوطة مرة واحدة أو أكثر. هذه هي أول مجموعة الالتقاط.

العودة إلى الأعلى

راجع أيضًا:

المرجع

System.Text.RegularExpressions

المبادئ

عناصر اللغة العاديه

موارد أخرى

التعبيرات العادية في .NET Framework