Regex.Split Regex.Split Regex.Split Regex.Split Method

定義

在規則運算式比對所定義的位置,將輸入字串分割成子字串陣列。Splits an input string into an array of substrings at the positions defined by a regular expression match.

多載

Split(String, String, RegexOptions, TimeSpan) Split(String, String, RegexOptions, TimeSpan) Split(String, String, RegexOptions, TimeSpan) Split(String, String, RegexOptions, TimeSpan)

在指定的規則運算式模式所定義的位置,將輸入字串分割成子字串陣列。Splits an input string into an array of substrings at the positions defined by a specified regular expression pattern. 如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

Split(String, String, RegexOptions) Split(String, String, RegexOptions) Split(String, String, RegexOptions) Split(String, String, RegexOptions)

在指定的規則運算式模式所定義的位置,將輸入字串分割成子字串陣列。Splits an input string into an array of substrings at the positions defined by a specified regular expression pattern. 指定的選項會修改符合的作業。Specified options modify the matching operation.

Split(String, Int32, Int32) Split(String, Int32, Int32) Split(String, Int32, Int32) Split(String, Int32, Int32)

Regex 建構函式中指定的規則運算式所定義的位置,以指定的最大次數來將輸入字串分隔成子字串的陣列。Splits an input string a specified maximum number of times into an array of substrings, at the positions defined by a regular expression specified in the Regex constructor. 規則運算式模式從輸入字串中指定的字元位置開始搜尋。The search for the regular expression pattern starts at a specified character position in the input string.

Split(String, Int32) Split(String, Int32) Split(String, Int32) Split(String, Int32)

Regex 建構函式中指定的規則運算式所定義的位置,以指定的最大次數來將輸入字串分隔成子字串的陣列。Splits an input string a specified maximum number of times into an array of substrings, at the positions defined by a regular expression specified in the Regex constructor.

Split(String) Split(String) Split(String) Split(String)

Regex 建構函式中指定之規則運算式模式所定義的位置,將輸入字串分隔成子字串的陣列。Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.

Split(String, String) Split(String, String) Split(String, String) Split(String, String)

在規則運算式模式所定義的位置,將輸入字串分割成子字串陣列。Splits an input string into an array of substrings at the positions defined by a regular expression pattern.

Split(String, String, RegexOptions, TimeSpan) Split(String, String, RegexOptions, TimeSpan) Split(String, String, RegexOptions, TimeSpan) Split(String, String, RegexOptions, TimeSpan)

在指定的規則運算式模式所定義的位置,將輸入字串分割成子字串陣列。Splits an input string into an array of substrings at the positions defined by a specified regular expression pattern. 如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

public:
 static cli::array <System::String ^> ^ Split(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public static string[] Split (string input, string pattern, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
static member Split : string * string * System.Text.RegularExpressions.RegexOptions * TimeSpan -> string[]
Public Shared Function Split (input As String, pattern As String, options As RegexOptions, matchTimeout As TimeSpan) As String()

參數

input
String String String String

要分隔的字串。The string to split.

pattern
String String String String

要比對的規則運算式模式。The regular expression pattern to match.

options
RegexOptions RegexOptions RegexOptions RegexOptions

列舉值的位元組合,提供用於比對的選項。A bitwise combination of the enumeration values that provide options for matching.

matchTimeout
TimeSpan TimeSpan TimeSpan TimeSpan

逾時間隔,若要表示此方法不應逾時則為 InfiniteMatchTimeoutA time-out interval, or InfiniteMatchTimeout to indicate that the method should not time out.

傳回

String[]

字串陣列。A string array.

例外狀況

發生規則運算式剖析錯誤。A regular expression parsing error occurred.

inputpatternnullinput or pattern is null.

options 不是 RegexOptions 值的有效位元組合。options is not a valid bitwise combination of RegexOptions values.

-或--or- matchTimeout 為負數、零或約大於 24 天。matchTimeout is negative, zero, or greater than approximately 24 days.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

備註

方法與String.Split(Char[])方法類似, 不同之處在于會Regex.Split在正則運算式所決定的分隔符號 (而不是一組字元) 上分割字串。 Regex.SplitThe Regex.Split methods are similar to the String.Split(Char[]) method, except that Regex.Split splits the string at a delimiter determined by a regular expression instead of a set of characters. 此字串會盡可能分割最多次。The string is split as many times as possible. 如果找不到分隔符號, 則傳回值會包含一個元素, 其值為input原始字串。If no delimiter is found, the return value contains one element whose value is the original input string.

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 如需正則運算式的詳細資訊, 請參閱.NET Framework 正則運算式正則運算式語言-快速參考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.

重要

在靜態Split方法的呼叫中使用編譯的正則運算式會自動快取。Compiled regular expressions used in calls to static Split methods are automatically cached. 若要自行管理已編譯之正則運算式的存留期Split , 請使用實例方法。To manage the lifetime of compiled regular expressions yourself, use the instance Split methods.

如果有多個相符專案彼此相鄰, 則會將空字串插入陣列中。If multiple matches are adjacent to one another, an empty string is inserted into the array. 例如, 將字串分割成單一連字號, 會導致傳回的陣列在找到兩個相鄰連字號的位置包含空字串。For example, splitting a string on a single hyphen causes the returned array to include an empty string in the position where two adjacent hyphens are found.

如果在輸入字串的開頭或結尾找到相符項, 則會在傳回陣列的開頭或結尾包含空字串。If a match is found at the beginning or the end of the input string, an empty string is included at the beginning or the end of the returned array. 下列範例會使用正則運算式模式[a-z]+ , 將輸入字串分割成任何大寫或小寫字母字元。The following example uses the regular expression pattern [a-z]+ to split an input string on any uppercase or lowercase alphabetic character. 因為字串的開頭和結尾都是相符的字母字元, 所以傳回陣列的第一個和最後一個元素的String.Empty值是。Because the string begins and ends with matching alphabetic characters, the value of the first and last element of the returned array is String.Empty.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = "[a-z]+";
      string input = "Abc1234Def5678Ghi9012Jklm";
      string[] result = Regex.Split(input, pattern, 
                                    RegexOptions.IgnoreCase,
                                    TimeSpan.FromMilliseconds(500));
      for (int ctr = 0; ctr < result.Length; ctr++) {
         Console.Write("'{0}'", result[ctr]);
         if (ctr < result.Length - 1) 
            Console.Write(", ");
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//       '', '1234', '5678', '9012', ''
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "[a-z]+"
      Dim input As String = "Abc1234Def5678Ghi9012Jklm"
      Dim result() As String = Regex.Split(input, pattern, 
                                           RegexOptions.IgnoreCase,
                                           TimeSpan.FromMilliseconds(500))
      For ctr As Integer = 0 To result.Length - 1
         Console.Write("'{0}'", result(ctr))
         If ctr < result.Length - 1 Then Console.Write(", ")
      Next
      Console.WriteLine()
   End Sub               
End Module
' The example displays the following output:
'       '', '1234', '5678', '9012', ''

如果在Regex.Split運算式中使用捕捉括弧, 則產生的字串陣列中會包含任何已捕獲的文字。If capturing parentheses are used in a Regex.Split expression, any captured text is included in the resulting string array. 例如, 如果您將字串 "梅紅-梨" (位於捕捉括弧內的連字號) 分割, 則傳回的陣列會包含包含連字號的 string 元素。For example, if you split the string "plum-pear" on a hyphen placed within capturing parentheses, the returned array includes a string element that contains the hyphen.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "plum-pear";
      string pattern = "(-)";

      string[] substrings = Regex.Split(input, pattern);    // Split on hyphens
      foreach (string match in substrings)
      {
         Console.WriteLine("'{0}'", match);
      }
   }
}
// The example displays the following output:
//    'plum'
//    '-'
//    'pear'      
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "plum-pear"
      Dim pattern As String = "(-)" 
      
      Dim substrings() As String = Regex.Split(input, pattern)    ' Split on hyphens.
      For Each match As String In substrings
         Console.WriteLine("'{0}'", match)
      Next
   End Sub
End Module
' The method writes the following to the console:
'    'plum'
'    '-'
'    'pear'      

不過, 當正則運算式模式包含多組捕捉括弧時, 這個方法的行為取決於 .NET Framework 的版本。However, when the regular expression pattern includes multiple sets of capturing parentheses, the behavior of this method depends on the version of the .NET Framework. 在 .NET Framework 1.0 和1.1 中, 如果在第一組捕捉括弧內找不到相符項, 則傳回的陣列中不會包含來自其他捕捉括弧的已捕捉文字。In the .NET Framework 1.0 and 1.1, if a match is not found within the first set of capturing parentheses, captured text from additional capturing parentheses is not included in the returned array. 從 .NET Framework 2.0 開始, 所有已捕捉的文字也會加入至傳回的陣列。Starting with the .NET Framework 2.0, all captured text is also added to the returned array. 例如, 下列程式碼會使用兩組捕捉括弧, 從日期字串中解壓縮日期的專案, 包括日期分隔符號。For example, the following code uses two sets of capturing parentheses to extract the elements of a date, including the date delimiters, from a date string. 第一組捕捉括弧會捕捉連字號, 而第二組則會捕捉正斜線。The first set of capturing parentheses captures the hyphen, and the second set captures the forward slash. 如果範例程式碼是在 .NET Framework 1.0 或1.1 之下編譯並執行, 則會排除斜線字元;如果編譯並在 .NET Framework 2.0 或更新版本下執行, 則會包含它們。If the example code is compiled and run under the .NET Framework 1.0 or 1.1, it excludes the slash characters; if it is compiled and run under the .NET Framework 2.0 or later versions, it includes them.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = @"07/14/2007";   
      string pattern = @"(-)|(/)";

      foreach (string result in Regex.Split(input, pattern)) 
      {
         Console.WriteLine("'{0}'", result);
      }
   }
}
// In .NET 1.0 and 1.1, the method returns an array of
// 3 elements, as follows:
//    '07'
//    '14'
//    '2007'
//
// In .NET 2.0 and later, the method returns an array of
// 5 elements, as follows:
//    '07'
//    '/'
//    '14'
//    '/'
//    '2007' 
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "07/14/2007"   
      Dim pattern As String = "(-)|(/)"
      For Each result As String In Regex.Split(input, pattern) 
         Console.WriteLine("'{0}'", result)
      Next
   End Sub
End Module
' In .NET 1.0 and 1.1, the method returns an array of
' 3 elements, as follows:
'    '07'
'    '14'
'    '2007'
'
' In .NET 2.0 and later, the method returns an array of
' 5 elements, as follows:
'    '07'
'    '/'
'    '14'
'    '/'
'    '2007' 

如果正則運算式可以符合空字串, 會Split將字串分割成單一字元字串的陣列, 因為在每個位置都可以找到空的字串分隔符號。If the regular expression can match the empty string, Split will split the string into an array of single-character strings because the empty string delimiter can be found at every location.

matchTimeout參數會指定模式比對方法應該在超時之前嘗試尋找相符的時間長度。設定逾時間隔, 可防止依賴過量回溯的正則運算式在處理包含接近相符專案的輸入時停止回應。The matchTimeout parameter specifies how long a pattern matching method should try to find a match before it times out. Setting a time-out interval prevents regular expressions that rely on excessive backtracking from appearing to stop responding when they process input that contains near matches. 如需詳細資訊, 請參閱正則運算式和回溯的最佳做法For more information, see Best Practices for Regular Expressions and Backtracking. 如果在該時間間隔內找不到相符的結果, 則RegexMatchTimeoutException方法會擲回例外狀況。If no match is found in that time interval, the method throws a RegexMatchTimeoutException exception. matchTimeout針對方法執行所在的應用程式域, 覆寫任何定義的預設超時值。matchTimeout overrides any default time-out value defined for the application domain in which the method executes.

給呼叫者的注意事項

我們建議您將matchTimeout參數設定為適當的值, 例如兩秒。We recommend that you set the matchTimeout parameter to an appropriate value, such as two seconds. 如果您藉由指定InfiniteMatchTimeout來停用超時, 則正則運算式引擎可提供稍微較佳的效能。If you disable time-outs by specifying InfiniteMatchTimeout, the regular expression engine offers slightly better performance. 不過, 只有在下列情況下, 您才應該停用超時:However, you should disable time-outs only under the following conditions: -當正則運算式所處理的輸入衍生自已知且受信任的來源, 或包含靜態文字時。- When the input processed by a regular expression is derived from a known and trusted source or consists of static text. 這會排除使用者動態輸入的文字。This excludes text that has been dynamically input by users.

-當正則運算式模式經過徹底測試, 以確保它能有效率地處理相符、不相符和接近的相符專案。- When the regular expression pattern has been thoroughly tested to ensure that it efficiently handles matches, non-matches, and near matches.

-當正則運算式模式未包含任何已知在處理接近相符專案時造成過多回溯的語言元素時。- When the regular expression pattern contains no language elements that are known to cause excessive backtracking when processing a near match.

另請參閱

Split(String, String, RegexOptions) Split(String, String, RegexOptions) Split(String, String, RegexOptions) Split(String, String, RegexOptions)

在指定的規則運算式模式所定義的位置,將輸入字串分割成子字串陣列。Splits an input string into an array of substrings at the positions defined by a specified regular expression pattern. 指定的選項會修改符合的作業。Specified options modify the matching operation.

public:
 static cli::array <System::String ^> ^ Split(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options);
public static string[] Split (string input, string pattern, System.Text.RegularExpressions.RegexOptions options);
static member Split : string * string * System.Text.RegularExpressions.RegexOptions -> string[]
Public Shared Function Split (input As String, pattern As String, options As RegexOptions) As String()

參數

input
String String String String

要分隔的字串。The string to split.

pattern
String String String String

要比對的規則運算式模式。The regular expression pattern to match.

options
RegexOptions RegexOptions RegexOptions RegexOptions

列舉值的位元組合,提供用於比對的選項。A bitwise combination of the enumeration values that provide options for matching.

傳回

String[]

字串的陣列。An array of strings.

例外狀況

發生規則運算式剖析錯誤。A regular expression parsing error occurred.

inputpatternnullinput or pattern is null.

options 不是 RegexOptions 值的有效位元組合。options is not a valid bitwise combination of RegexOptions values.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

備註

方法與String.Split(Char[])方法類似, 不同之處在于會Regex.Split在正則運算式所決定的分隔符號 (而不是一組字元) 上分割字串。 Regex.SplitThe Regex.Split methods are similar to the String.Split(Char[]) method, except that Regex.Split splits the string at a delimiter determined by a regular expression instead of a set of characters. 此字串會盡可能分割最多次。The string is split as many times as possible. 如果找不到分隔符號, 則傳回值會包含一個元素, 其值為input原始字串。If no delimiter is found, the return value contains one element whose value is the original input string.

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 如需正則運算式的詳細資訊, 請參閱.NET Framework 正則運算式正則運算式語言-快速參考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.

重要

在靜態Split方法的呼叫中使用編譯的正則運算式會自動快取。Compiled regular expressions used in calls to static Split methods are automatically cached. 若要自行管理已編譯之正則運算式的存留期Split , 請使用實例方法。To manage the lifetime of compiled regular expressions yourself, use the instance Split methods.

如果有多個相符專案彼此相鄰, 則會將空字串插入陣列中。If multiple matches are adjacent to one another, an empty string is inserted into the array. 例如, 將字串分割成單一連字號, 會導致傳回的陣列在找到兩個相鄰連字號的位置包含空字串。For example, splitting a string on a single hyphen causes the returned array to include an empty string in the position where two adjacent hyphens are found.

如果在輸入字串的開頭或結尾找到相符項, 則會在傳回陣列的開頭或結尾包含空字串。If a match is found at the beginning or the end of the input string, an empty string is included at the beginning or the end of the returned array. 下列範例會使用正則運算式模式[a-z]+ , 將輸入字串分割成任何大寫或小寫字母字元。The following example uses the regular expression pattern [a-z]+ to split an input string on any uppercase or lowercase alphabetic character. 因為字串的開頭和結尾都是相符的字母字元, 所以傳回陣列的第一個和最後一個元素的String.Empty值是。Because the string begins and ends with matching alphabetic characters, the value of the first and last element of the returned array is String.Empty.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = "[a-z]+";
      string input = "Abc1234Def5678Ghi9012Jklm";
      string[] result = Regex.Split(input, pattern, 
                                    RegexOptions.IgnoreCase);
      for (int ctr = 0; ctr < result.Length; ctr++) {
         Console.Write("'{0}'", result[ctr]);
         if (ctr < result.Length - 1) 
            Console.Write(", ");
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//       '', '1234', '5678', '9012', ''
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "[a-z]+"
      Dim input As String = "Abc1234Def5678Ghi9012Jklm"
      Dim result() As String = Regex.Split(input, pattern, 
                                           RegexOptions.IgnoreCase)
      For ctr As Integer = 0 To result.Length - 1
         Console.Write("'{0}'", result(ctr))
         If ctr < result.Length - 1 Then Console.Write(", ")
      Next
      Console.WriteLine()
   End Sub               
End Module
' The example displays the following output:
'       '', '1234', '5678', '9012', ''

如果在Regex.Split運算式中使用捕捉括弧, 則產生的字串陣列中會包含任何已捕獲的文字。If capturing parentheses are used in a Regex.Split expression, any captured text is included in the resulting string array. 例如, 如果您將字串 "梅紅-梨" (位於捕捉括弧內的連字號) 分割, 則傳回的陣列會包含包含連字號的 string 元素。For example, if you split the string "plum-pear" on a hyphen placed within capturing parentheses, the returned array includes a string element that contains the hyphen.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "plum-pear";
      string pattern = "(-)";

      string[] substrings = Regex.Split(input, pattern);    // Split on hyphens
      foreach (string match in substrings)
      {
         Console.WriteLine("'{0}'", match);
      }
   }
}
// The example displays the following output:
//    'plum'
//    '-'
//    'pear'      
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "plum-pear"
      Dim pattern As String = "(-)" 
      
      Dim substrings() As String = Regex.Split(input, pattern)    ' Split on hyphens.
      For Each match As String In substrings
         Console.WriteLine("'{0}'", match)
      Next
   End Sub
End Module
' The method writes the following to the console:
'    'plum'
'    '-'
'    'pear'      

不過, 當正則運算式模式包含多組捕捉括弧時, 這個方法的行為取決於 .NET Framework 的版本。However, when the regular expression pattern includes multiple sets of capturing parentheses, the behavior of this method depends on the version of the .NET Framework. 在 .NET Framework 1.0 和1.1 中, 如果在第一組捕捉括弧內找不到相符項, 則傳回的陣列中不會包含來自其他捕捉括弧的已捕捉文字。In the .NET Framework 1.0 and 1.1, if a match is not found within the first set of capturing parentheses, captured text from additional capturing parentheses is not included in the returned array. 從 .NET Framework 2.0 開始, 所有已捕捉的文字也會加入至傳回的陣列。Starting with the .NET Framework 2.0, all captured text is also added to the returned array. 例如, 下列程式碼會使用兩組捕捉括弧, 從日期字串中解壓縮日期的專案, 包括日期分隔符號。For example, the following code uses two sets of capturing parentheses to extract the elements of a date, including the date delimiters, from a date string. 第一組捕捉括弧會捕捉連字號, 而第二組則會捕捉正斜線。The first set of capturing parentheses captures the hyphen, and the second set captures the forward slash. 如果範例程式碼是在 .NET Framework 1.0 或1.1 之下編譯並執行, 則會排除斜線字元;如果編譯並在 .NET Framework 2.0 或更新版本下執行, 則會包含它們。If the example code is compiled and run under the .NET Framework 1.0 or 1.1, it excludes the slash characters; if it is compiled and run under the .NET Framework 2.0 or later versions, it includes them.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = @"07/14/2007";   
      string pattern = @"(-)|(/)";

      foreach (string result in Regex.Split(input, pattern)) 
      {
         Console.WriteLine("'{0}'", result);
      }
   }
}
// In .NET 1.0 and 1.1, the method returns an array of
// 3 elements, as follows:
//    '07'
//    '14'
//    '2007'
//
// In .NET 2.0 and later, the method returns an array of
// 5 elements, as follows:
//    '07'
//    '/'
//    '14'
//    '/'
//    '2007' 
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "07/14/2007"   
      Dim pattern As String = "(-)|(/)"
      For Each result As String In Regex.Split(input, pattern) 
         Console.WriteLine("'{0}'", result)
      Next
   End Sub
End Module
' In .NET 1.0 and 1.1, the method returns an array of
' 3 elements, as follows:
'    '07'
'    '14'
'    '2007'
'
' In .NET 2.0 and later, the method returns an array of
' 5 elements, as follows:
'    '07'
'    '/'
'    '14'
'    '/'
'    '2007' 

如果正則運算式可以符合空字串, 會Split將字串分割成單一字元字串的陣列, 因為在每個位置都可以找到空的字串分隔符號。If the regular expression can match the empty string, Split will split the string into an array of single-character strings because the empty string delimiter can be found at every location.

如果分割作業的執行時間超出為呼叫方法的應用程式域指定的逾時間隔, 就會擲回例外狀況(exception)。RegexMatchTimeoutExceptionThe RegexMatchTimeoutException exception is thrown if the execution time of the split operation exceeds the time-out interval specified for the application domain in which the method is called. 如果在應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況。If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

給呼叫者的注意事項

這個方法會在與呼叫方法之應用程式域的預設超時值相等的間隔時間之後發生。This method times out after an interval that is equal to the default time-out value of the application domain in which the method is called. 如果未針對應用程式定義域定義逾時值,則使用值 InfiniteMatchTimeout,使方法不會逾時。If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. 在模式比對上分割文字的建議靜態方法是Split(String, String, RegexOptions, TimeSpan), 可讓您設定逾時間隔。The recommended static method for splitting text on a pattern match is Split(String, String, RegexOptions, TimeSpan), which lets you set the time-out interval.

另請參閱

Split(String, Int32, Int32) Split(String, Int32, Int32) Split(String, Int32, Int32) Split(String, Int32, Int32)

Regex 建構函式中指定的規則運算式所定義的位置,以指定的最大次數來將輸入字串分隔成子字串的陣列。Splits an input string a specified maximum number of times into an array of substrings, at the positions defined by a regular expression specified in the Regex constructor. 規則運算式模式從輸入字串中指定的字元位置開始搜尋。The search for the regular expression pattern starts at a specified character position in the input string.

public:
 cli::array <System::String ^> ^ Split(System::String ^ input, int count, int startat);
public string[] Split (string input, int count, int startat);
member this.Split : string * int * int -> string[]
Public Function Split (input As String, count As Integer, startat As Integer) As String()

參數

input
String String String String

要分隔的字串。The string to be split.

count
Int32 Int32 Int32 Int32

分隔作業可以發生的最多次數。The maximum number of times the split can occur.

startat
Int32 Int32 Int32 Int32

在輸入字串中要開始搜尋的字元位置。The character position in the input string where the search will begin.

傳回

String[]

字串的陣列。An array of strings.

例外狀況

startat 小於零或大於 input 的長度。startat is less than zero or greater than the length of input.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

備註

方法與String.Split方法類似, 不同之處在于會Regex.Split在正則運算式所決定的分隔符號 (而不是一組字元) 上分割字串。 Regex.SplitThe Regex.Split methods are similar to the String.Split method, except that Regex.Split splits the string at a delimiter determined by a regular expression instead of a set of characters. 參數會指定將input字串分割成的子字串數目上限; 最後一個字串包含字串的解除餘數。 countThe count parameter specifies the maximum number of substrings into which the input string is split; the last string contains the unsplit remainder of the string. count值為零會提供盡可能分割的預設行為。A count value of zero provides the default behavior of splitting as many times as possible. startat參數會定義開始搜尋第一個分隔符號的點 (這可以用來略過前置空白字元)。The startat parameter defines the point at which the search for the first delimiter begins (this can be used for skipping leading white space).

如果在字串中的count+ 1 位置找不到相符專案, 則方法會傳回input包含字串的單一元素陣列。If no matches are found from the count+1 position in the string, the method returns a one-element array that contains the input string. 如果找到一個或多個相符專案, 則傳回之陣列的第一個專案會包含字串中第一個字元的第一個部分 (最多在比對之前的一個字元)。If one or more matches are found, the first element of the returned array contains the first portion of the string from the first character up to one character before the match.

如果有多個相符專案彼此相鄰, 而且找到的相符專案數至少有兩個小於count, 則會在陣列中插入空字串。If multiple matches are adjacent to one another and the number of matches found is at least two less than count, an empty string is inserted into the array. 同樣地, 如果在中找到startat相符專案 (也就是字串中的第一個字元), 則傳回陣列的第一個元素會是空字串。Similarly, if a match is found at startat, which is the first character in the string, the first element of the returned array is an empty string. 也就是說, 在判斷相符子字串的數目是否等於count時, 會計算由相鄰相符專案所產生的空字串。That is, empty strings that result from adjacent matches are counted in determining whether the number of matched substrings equals count. 在下列範例中, 正則運算式\d+用來尋找字串中數位字元第一個子字串的開始位置, 然後從該位置開始分割最多三次的字串。In the following example, the regular expression \d+ is used to find the starting position of the first substring of numeric characters in a string, and then to split the string a maximum of three times starting at that position. 因為正則運算式模式會比對輸入字串的開頭, 所以傳回的字串陣列會包含空字串、五個字元的字母字串和字串的其餘部分。Because the regular expression pattern matches the beginning of the input string, the returned string array consists of an empty string, a five-character alphabetic string, and the remainder of the string,

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\d+";
      Regex rgx = new Regex(pattern);
      string input = "123ABCDE456FGHIJ789KLMNO012PQRST";
      Match m = rgx.Match(input);
      if (m.Success) { 
         int startAt = m.Index;
         string[] result = rgx.Split(input, 3, startAt);
         for (int ctr = 0; ctr < result.Length; ctr++) {
            Console.Write("'{0}'", result[ctr]);
            if (ctr < result.Length - 1)
               Console.Write(", ");
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output:
//       '', 'ABCDE', 'FGHIJKL789MNOPQ012'
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\d+"
      Dim rgx As New Regex(pattern)
      Dim input As String = "123ABCDE456FGHIJ789KLMNO012PQRST"
      Dim m As Match = rgx.Match(input)
      If m.Success Then 
         Dim startAt As Integer = m.Index
         Dim result() As String = rgx.Split(input, 3, startAt)
         For ctr As Integer = 0 To result.Length - 1
            Console.Write("'{0}'", result(ctr))
            If ctr < result.Length - 1 Then Console.Write(", ")
         Next
         Console.WriteLine()
      End If
   End Sub               
End Module
' The example displays the following output:
'       '', 'ABCDE', 'FGHIJKL789MNOPQ012'

如果在正則運算式中使用捕捉括弧, 任何已捕獲的文字都會包含在分割字串的陣列中。If capturing parentheses are used in a regular expression, any captured text is included in the array of split strings. 不過, 任何包含已捕捉之文字的陣列元素, 都不會在判斷是否已達到count相符專案數目時計算。However, any array elements that contain captured text are not counted in determining whether the number of matches has reached count. 例如, 從字串中的字元15開始, 將字串 ' "apricot-梅紅-石榴-pineapple-peach" 分割成最多四個子字串, 如下列程式碼所示。For example, splitting the string '"apple-apricot-plum-pear-pomegranate-pineapple-peach" into a maximum of four substrings beginning at character 15 in the string results in a seven-element array, as the following code shows.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "(-)"
      Dim input As String = "apple-apricot-plum-pear-pomegranate-pineapple-peach"

      Dim regex As Regex = New Regex(pattern)    
      ' Split on hyphens from 15th character on
      Dim substrings() As String = regex.Split(input, 4, 15)
      For Each match As String In substrings
         Console.WriteLine("'{0}'", match)
      Next
   End Sub  
End Module
' The example displays the following output:
'    'apple-apricot-plum'
'    '-'
'    'pear'
'    '-'
'    'pomegranate'
'    '-'
'    'pineapple-peach'      

不過, 當正則運算式模式包含多組捕捉括弧時, 這個方法的行為取決於 .NET Framework 的版本。However, when the regular expression pattern includes multiple sets of capturing parentheses, the behavior of this method depends on the version of the .NET Framework. 在 .NET Framework 1.0 和1.1 中, 如果在第一組捕捉括弧內找不到相符項, 則傳回的陣列中不會包含來自其他捕捉括弧的已捕捉文字。In .NET Framework 1.0 and 1.1, if a match is not found within the first set of capturing parentheses, captured text from additional capturing parentheses is not included in the returned array. 從 .NET Framework 2.0 開始, 所有已捕捉的文字也會加入至傳回的陣列。Starting with the .NET Framework 2.0, all captured text is also added to the returned array. 例如, 下列程式碼會使用兩組捕捉括弧, 將字串中的個別單字解壓縮。For example, the following code uses two sets of capturing parentheses to extract the individual words in a string. 第一組捕捉括弧會捕捉連字號, 而第二組則會捕捉到分隔號。The first set of capturing parentheses captures the hyphen, and the second set captures the vertical bar. 如果範例程式碼是在 .NET Framework 1.0 或1.1 之下編譯並執行, 則會排除分隔號字元;如果編譯並在 .NET Framework 2.0 或更新版本下執行, 則會包含它們。If the example code is compiled and run under the .NET Framework 1.0 or 1.1, it excludes the vertical bar characters; if it is compiled and run under the .NET Framework 2.0 or later versions, it includes them.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = "(-)|([|])";     // possible delimiters found in string
      string input = "apple|apricot|plum|pear|pomegranate|pineapple|peach";

      Regex regex = new Regex(pattern);    
      // Split on delimiters from 15th character on
      string[] substrings = regex.Split(input, 4, 15);
      foreach (string match in substrings)
      {
         Console.WriteLine("'{0}'", match);
      }
   }
}
// In .NET 2.0 and later, the method returns an array of
// 7 elements, as follows:
//    apple|apricot|plum'
//    '|'
//    'pear'
//    '|'
//    'pomegranate'
//    '|'
//    'pineapple|peach'
// In .NET 1.0 and 1.1, the method returns an array of
// 4 elements, as follows:
//    'apple|apricot|plum'
//    'pear'
//    'pomegranate'
//    'pineapple|peach'
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "(-)|([|])"   ' possible delimiters found in string
      Dim input As String = "apple|apricot|plum|pear|pomegranate|pineapple|peach"

      Dim regex As Regex = New Regex(pattern)    
      ' Split on delimiters from 15th character on
      Dim substrings() As String = regex.Split(input, 4, 15)
      For Each match As String In substrings
         Console.WriteLine("'{0}'", match)
      Next
   End Sub
End Module
' In .NET 2.0, the method returns an array of
' 7 elements, as follows:
'    apple|apricot|plum'
'    '|'
'    'pear'
'    '|'
'    'pomegranate'
'    '|'
'    'pineapple|peach'
' In .NET 1.0 and 1.1, the method returns an array of
' 4 elements, as follows:
'    'apple|apricot|plum'
'    'pear'
'    'pomegranate'
'    'pineapple|peach'

如果正則運算式可以符合空字串, 會Split將字串分割成單一字元字串的陣列, 因為在每個位置都可以找到空的字串分隔符號。If the regular expression can match the empty string, Split will split the string into an array of single-character strings because the empty string delimiter can be found at every location. 下列範例會將字串 "character" 分割成輸入字串所包含的多個元素, 開頭為 "a" 字元。The following example splits the string "characters" into as many elements as the input string contains, starting with the character "a". 由於 null 字串符合輸入字串的結尾, 因此會在傳回的陣列結尾插入 null 字串。Because the null string matches the end of the input string, a null string is inserted at the end of the returned array.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "characters";
      Regex regex = new Regex("");
      string[] substrings = regex.Split(input, input.Length, input.IndexOf("a"));
      Console.Write("{");
      for(int ctr = 0; ctr < substrings.Length; ctr++)
      {
         Console.Write(substrings[ctr]);
         if (ctr < substrings.Length - 1)
            Console.Write(", ");
      }
      Console.WriteLine("}");
   }
}
// The example displays the following output:   
//    {, c, h, a, r, a, c, t, e, rs}
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "characters"
      Dim regex As New Regex("")
      Dim substrings() As String = regex.Split(input, input.Length, _
                                               input.IndexOf("a"))
      Console.Write("{")
      For ctr As Integer = 0 to substrings.Length - 1
         Console.Write(substrings(ctr))
         If ctr < substrings.Length - 1 Then Console.Write(", ")
      Next
      Console.WriteLine("}")
   End Sub
End Module
' The example produces the following output:   
'    {, c, h, a, r, a, c, t, e, rs}

如果分割作業的執行時間超過由此Regex.Regex(String, RegexOptions, TimeSpan)函式所指定的逾時間隔, 就會擲回例外狀況。RegexMatchTimeoutExceptionThe RegexMatchTimeoutException exception is thrown if the execution time of the split operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

另請參閱

Split(String, Int32) Split(String, Int32) Split(String, Int32) Split(String, Int32)

Regex 建構函式中指定的規則運算式所定義的位置,以指定的最大次數來將輸入字串分隔成子字串的陣列。Splits an input string a specified maximum number of times into an array of substrings, at the positions defined by a regular expression specified in the Regex constructor.

public:
 cli::array <System::String ^> ^ Split(System::String ^ input, int count);
public string[] Split (string input, int count);
member this.Split : string * int -> string[]
Public Function Split (input As String, count As Integer) As String()

參數

input
String String String String

要分隔的字串。The string to be split.

count
Int32 Int32 Int32 Int32

分隔作業可以發生的最多次數。The maximum number of times the split can occur.

傳回

String[]

字串的陣列。An array of strings.

例外狀況

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

備註

方法與String.Split方法類似, 不同之處在于會Regex.Split在正則運算式所決定的分隔符號 (而不是一組字元) 上分割字串。 Regex.SplitThe Regex.Split methods are similar to the String.Split method, except that Regex.Split splits the string at a delimiter determined by a regular expression instead of a set of characters. 參數會指定可分割input字串的子字串數目上限; 最後一個字串包含字串的解除餘數。 countThe count parameter specifies the maximum number of substrings into which the input string can be split; the last string contains the unsplit remainder of the string. count值為零會提供盡可能分割的預設行為。A count value of zero provides the default behavior of splitting as many times as possible.

如果有多個相符專案彼此相鄰input, 或是在的開頭或結尾找到相符專案, 而且找到的相符專案數至少count小於兩個, 則會在陣列中插入空字串。If multiple matches are adjacent to one another or if a match is found at the beginning or end of input, and the number of matches found is at least two less than count, an empty string is inserted into the array. 也就是說, 在輸入字串的開頭或結尾, 由相鄰相符專案或符合專案所產生的空字串, 會在判斷相符子字串的數目是否等於count時計算。That is, empty strings that result from adjacent matches or from matches at the beginning or end of the input string are counted in determining whether the number of matched substrings equals count. 在下列範例中, 正則運算式/d+是用來將包含一或多個十進位數的輸入字串分割成最多三個子字串。In the following example, the regular expression /d+ is used to split an input string that includes one or more decimal digits into a maximum of three substrings. 由於輸入字串的開頭符合正則運算式模式, 因此第一個陣列元素會包含String.Empty, 第二個則包含輸入字串中的第一組字母字元, 而第三個包含字串的其餘部分。這會在第三個相符的後面。Because the beginning of the input string matches the regular expression pattern, the first array element contains String.Empty, the second contains the first set of alphabetic characters in the input string, and the third contains the remainder of the string that follows the third match.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\d+";
      Regex rgx = new Regex(pattern);
      string input = "123ABCDE456FGHIJKL789MNOPQ012";
      
      string[] result = rgx.Split(input, 3);
      for (int ctr = 0; ctr < result.Length; ctr++) {
         Console.Write("'{0}'", result[ctr]);
         if (ctr < result.Length - 1) 
            Console.Write(", ");
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//       '', 'ABCDE', 'FGHIJKL789MNOPQ012'
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\d+"
      Dim rgx As New Regex(pattern)
      Dim input As String = "123ABCDE456FGHIJKL789MNOPQ012"
      
      Dim result() As String = rgx.Split(input, 3)
      For ctr As Integer = 0 To result.Length - 1
         Console.Write("'{0}'", result(ctr))
         If ctr < result.Length - 1 Then Console.Write(", ")
      Next
      Console.WriteLine()
   End Sub               
End Module
' The example displays the following output:
'       '', 'ABCDE', 'FGHIJKL789MNOPQ012'

如果在正則運算式中使用捕捉括弧, 任何已捕獲的文字都會包含在分割字串的陣列中。If capturing parentheses are used in a regular expression, any captured text is included in the array of split strings. 不過, 任何包含已捕捉之文字的陣列元素, 都不會在判斷是否已達到count相符專案數目時計算。However, any array elements that contain captured text are not counted in determining whether the number of matches has reached count. 例如, 將字串 "apricot-梅紅-梨-香蕉" 分割成最多四個子字串會產生七個元素的陣列, 如下列程式碼所示。For example, splitting the string "apple-apricot-plum-pear-banana" into a maximum of four substrings results in a seven-element array, as the following code shows.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = "(-)";
      string input = "apple-apricot-plum-pear-banana";
      Regex regex = new Regex(pattern);         // Split on hyphens.
      string[] substrings = regex.Split(input, 4);
      foreach (string match in substrings)
      {
         Console.WriteLine("'{0}'", match);
      }
   }
}
// The example displays the following output:
//       'apple'
//       '-'
//       'apricot'
//       '-'
//       'plum'
//       '-'
//       'pear-banana'      
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "(-)"
      Dim input As String = "apple-apricot-plum-pear-banana"
      Dim regex As Regex = New Regex(pattern)         ' Split on hyphens.
      Dim substrings() As String = regex.Split(input, 4)
      For Each match As String In substrings
         Console.WriteLine("'{0}'", match)
      Next
   End Sub
End Module
' The example displays the following output:
'    'apple'
'    '-'
'    'apricot'
'    '-'
'    'plum'
'    '-'
'    'pear-banana'      

不過, 當正則運算式模式包含多組捕捉括弧時, 這個方法的行為取決於 .NET Framework 的版本。However, when the regular expression pattern includes multiple sets of capturing parentheses, the behavior of this method depends on the version of the .NET Framework. 在 .NET Framework 1.0 和1.1 中, 傳回的陣列中只會包含第一組捕捉括弧中的已捕獲文字。In the .NET Framework 1.0 and 1.1, only captured text from the first set of capturing parentheses is included in the returned array. 從 .NET Framework 2.0 開始, 所有已捕捉的文字都會加入至傳回的陣列。Starting with the .NET Framework 2.0, all captured text is added to the returned array. 不過, 傳回的陣列中包含已捕捉之文字的元素, 不會在判斷相符的子字串數目count是否相等時計算。However, elements in the returned array that contain captured text are not counted in determining whether the number of matched substrings equals count. 例如, 在下列程式碼中, 正則運算式會使用兩組捕獲括弧, 從日期字串中解壓縮日期的專案。For example, in the following code, a regular expression uses two sets of capturing parentheses to extract the elements of a date from a date string. 第一組捕捉括弧會捕捉連字號, 而第二組則會捕捉正斜線。The first set of capturing parentheses captures the hyphen, and the second set captures the forward slash. 呼叫Split(String, Int32)方法之後, 會在傳回的陣列中指定最多兩個元素。The call to the Split(String, Int32) method then specifies a maximum of two elements in the returned array. 如果範例程式碼是在 .NET Framework 1.0 或1.1 之下編譯並執行, 則此方法會傳回兩個元素的字串陣列。If the example code is compiled and run under the .NET Framework 1.0 or 1.1, the method returns a two-element string array. 如果編譯並在 .NET Framework 2.0 或更新版本下執行, 則方法會傳回三個元素的字串陣列。If it is compiled and run under the .NET Framework 2.0 or later versions, the method returns a three-element string array.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = @"07/14/2007";   
      string pattern = @"(-)|(/)";
      Regex regex = new Regex(pattern);
      foreach (string result in regex.Split(input, 2)) 
      {
         Console.WriteLine("'{0}'", result);
      }
   }
}
// Under .NET 1.0 and 1.1, the method returns an array of
// 2 elements, as follows:
//    '07'
//    '14/2007'
//
// Under .NET 2.0 and later, the method returns an array of
// 3 elements, as follows:
//    '07'
//    '/'
//    '14/2007' 
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "07/14/2007"   
      Dim pattern As String = "(-)|(/)"
      Dim regex As Regex = New Regex(pattern)
      For Each result As String In regex.Split(input, 2) 
         Console.WriteLine("'{0}'", result)
      Next
   End Sub
End Module
' In .NET 1.0 and 1.1, the method returns an array of
' 2 elements, as follows:
'    '07'
'    '14/2007'
'
' In .NET 2.0 and later, the method returns an array of
' 3 elements, as follows:
'    '07'
'    '/'
'    '14/2007' 

如果正則運算式可以符合空字串, 會Split(String, Int32)將字串分割成單一字元字串的陣列, 因為在每個位置都可以找到空的字串分隔符號。If the regular expression can match the empty string, Split(String, Int32) will split the string into an array of single-character strings because the empty string delimiter can be found at every location. 下列範例會將字串 "字元" 分割成輸入字串中的多個元素。The following example splits the string "characters" into as many elements as there are in the input string. 因為 null 字串符合輸入字串的開頭, 所以會在傳回陣列的開頭插入 null 字串。Because the null string matches the beginning of the input string, a null string is inserted at the beginning of the returned array. 這會導致第十個元素包含在輸入字串結尾的兩個字元。This causes the tenth element to consist of the two characters at the end of the input string.

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "characters"
      Dim regex As New Regex("")
      Dim substrings() As String = regex.Split(input, input.Length)
      Console.Write("{")
      For ctr As Integer = 0 to substrings.Length - 1
         Console.Write(substrings(ctr))
         if ctr < substrings.Length - 1 Then Console.Write(", ")
      Next
      Console.WriteLine("}")
   End Sub
End Module
' The example displays the following output:   
'    {, c, h, a, r, a, c, t, e, rs}

如果分割作業的執行時間超過由此Regex.Regex(String, RegexOptions, TimeSpan)函式所指定的逾時間隔, 就會擲回例外狀況。RegexMatchTimeoutExceptionThe RegexMatchTimeoutException exception is thrown if the execution time of the split operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

另請參閱

Split(String) Split(String) Split(String) Split(String)

Regex 建構函式中指定之規則運算式模式所定義的位置,將輸入字串分隔成子字串的陣列。Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.

public:
 cli::array <System::String ^> ^ Split(System::String ^ input);
public string[] Split (string input);
member this.Split : string -> string[]
Public Function Split (input As String) As String()

參數

input
String String String String

要分隔的字串。The string to split.

傳回

String[]

字串的陣列。An array of strings.

例外狀況

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

備註

方法與String.Split(Char[])方法類似, 不同之處在于會Regex.Split在正則運算式所決定的分隔符號 (而不是一組字元) 上分割字串。 Regex.SplitThe Regex.Split methods are similar to the String.Split(Char[]) method, except that Regex.Split splits the string at a delimiter determined by a regular expression instead of a set of characters. 此字串會盡可能分割最多次。The string is split as many times as possible. 如果找不到分隔符號, 則傳回值會包含一個元素, 其值為原始輸入字串。If no delimiter is found, the return value contains one element whose value is the original input string.

如果有多個相符專案彼此相鄰, 則會將空字串插入陣列中。If multiple matches are adjacent to one another, an empty string is inserted into the array. 例如, 將字串分割成單一連字號, 會導致傳回的陣列在找到兩個相鄰連字號的位置包含空字串, 如下列程式碼所示。For example, splitting a string on a single hyphen causes the returned array to include an empty string in the position where two adjacent hyphens are found, as the following code shows.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      Regex regex = new Regex("-");         // Split on hyphens.
      string[] substrings = regex.Split("plum--pear");
      foreach (string match in substrings)
      {
         Console.WriteLine("'{0}'", match);
      }
   }
}
// The example displays the following output:
//    'plum'
//    ''
//    'pear'      
Imports System.Text.RegularExpressions

Module RegexSplit
   Public Sub Main()
      Dim regex As Regex = New Regex("-")         ' Split on hyphens.
      Dim substrings() As String = regex.Split("plum--pear")
      For Each match As String In substrings
         Console.WriteLine("'{0}'", match)
      Next
   End Sub
End Module
' The example displays the following output:
'    'plum'
'    ''
'    'pear'      

如果在輸入字串的開頭或結尾找到相符項, 則會在傳回陣列的開頭或結尾包含空字串。If a match is found at the beginning or the end of the input string, an empty string is included at the beginning or the end of the returned array. 下列範例會使用正則運算式模式\d+ , 將輸入字串分割為數字字元。The following example uses the regular expression pattern \d+ to split an input string on numeric characters. 因為字串的開頭和結尾都是相符的數位字元, 所以傳回陣列的第一個和最後一個元素的String.Empty值是。Because the string begins and ends with matching numeric characters, the value of the first and last element of the returned array is String.Empty.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\d+";
      Regex rgx = new Regex(pattern);
      string input = "123ABCDE456FGHIJKL789MNOPQ012";
      
      string[] result = rgx.Split(input);
      for (int ctr = 0; ctr < result.Length; ctr++) {
         Console.Write("'{0}'", result[ctr]);
         if (ctr < result.Length - 1) 
            Console.Write(", ");
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//       '', 'ABCDE', 'FGHIJKL', 'MNOPQ', ''
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\d+"
      Dim rgx As New Regex(pattern)
      Dim input As String = "123ABCDE456FGHIJKL789MNOPQ012"
      
      Dim result() As String = rgx.Split(input)
      For ctr As Integer = 0 To result.Length - 1
         Console.Write("'{0}'", result(ctr))
         If ctr < result.Length - 1 Then Console.Write(", ")
      Next
      Console.WriteLine()
   End Sub               
End Module
' The example displays the following output:
'       '', 'ABCDE', 'FGHIJKL', 'MNOPQ', ''

如果在Regex.Split運算式中使用捕捉括弧, 則產生的字串陣列中會包含任何已捕獲的文字。If capturing parentheses are used in a Regex.Split expression, any captured text is included in the resulting string array. 例如, 如果您將字串 "梅紅-梨" (位於捕捉括弧內的連字號) 分割, 則傳回的陣列會包含包含連字號的 string 元素。For example, if you split the string "plum-pear" on a hyphen placed within capturing parentheses, the returned array includes a string element that contains the hyphen.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      Regex regex = new Regex("(-)");         // Split on hyphens.
      string[] substrings = regex.Split("plum-pear");
      foreach (string match in substrings)
      {
         Console.WriteLine("'{0}'", match);
      }
   }
}
// The example displays the following output:
//    'plum'
//    '-'
//    'pear'      
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim regex As Regex = New Regex("(-)")          ' Split on hyphens.
      Dim substrings() As String = regex.Split("plum-pear")
      For Each match As String In substrings
         Console.WriteLine("'{0}'", match)
      Next
   End Sub
End Module
' The example displays the following output:
'    'plum'
'    '-'
'    'pear'      

不過, 當正則運算式模式包含多組捕捉括弧時, 這個方法的行為取決於 .NET Framework 的版本。However, when the regular expression pattern includes multiple sets of capturing parentheses, the behavior of this method depends on the version of the .NET Framework. 在 .NET Framework 1.0 和1.1 中, 如果在第一組捕捉括弧內找不到相符項, 則傳回的陣列中不會包含來自其他捕捉括弧的已捕捉文字。In the .NET Framework 1.0 and 1.1, if a match is not found within the first set of capturing parentheses, captured text from additional capturing parentheses is not included in the returned array. 從 .NET Framework 2.0 開始, 所有已捕捉的文字也會加入至傳回的陣列。Starting with the .NET Framework 2.0, all captured text is also added to the returned array. 例如, 下列程式碼會使用兩組捕捉括弧, 從日期字串中解壓縮日期的專案, 包括日期分隔符號。For example, the following code uses two sets of capturing parentheses to extract the elements of a date, including the date delimiters, from a date string. 第一組捕捉括弧會捕捉連字號, 而第二組則會捕捉正斜線。The first set of capturing parentheses captures the hyphen, and the second set captures the forward slash. 如果範例程式碼是在 .NET Framework 1.0 或1.1 之下編譯並執行, 則會排除斜線字元;如果編譯並在 .NET Framework 2.0 或更新版本下執行, 則會包含它們。If the example code is compiled and run under the .NET Framework 1.0 or 1.1, it excludes the slash characters; if it is compiled and run under the .NET Framework 2.0 or later versions, it includes them.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = @"07/14/2007";   
      string pattern = @"(-)|(/)";
      Regex regex = new Regex(pattern);
      foreach (string result in regex.Split(input)) 
      {
         Console.WriteLine("'{0}'", result);
      }
   }
}
// Under .NET 1.0 and 1.1, the method returns an array of
// 3 elements, as follows:
//    '07'
//    '14'
//    '2007'
//
// Under .NET 2.0 and later, the method returns an array of
// 5 elements, as follows:
//    '07'
//    '/'
//    '14'
//    '/'
//    '2007' 
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "07/14/2007"   
      Dim pattern As String = "(-)|(/)"
      Dim regex As Regex = New Regex(pattern)
      For Each result As String In regex.Split(input) 
         Console.WriteLine("'{0}'", result)
      Next
   End Sub
End Module
' In .NET 1.0 and 1.1, the method returns an array of
' 3 elements, as follows:
'    '07'
'    '14'
'    '2007'
'
' In .NET 2.0 and later, the method returns an array of
' 5 elements, as follows:
'    '07'
'    '/'
'    '14'
'    '/'
'    '2007' 

如果正則運算式可以符合空字串, 會Split(String)將字串分割成單一字元字串的陣列, 因為在每個位置都可以找到空的字串分隔符號。If the regular expression can match the empty string, Split(String) will split the string into an array of single-character strings because the empty string delimiter can be found at every location. 例如:For example:

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "characters";
      Regex regex = new Regex("");
      string[] substrings = regex.Split(input);
      Console.Write("{");
      for(int ctr = 0; ctr < substrings.Length; ctr++)
      {
         Console.Write(substrings[ctr]);
         if (ctr < substrings.Length - 1)
            Console.Write(", ");
      }
      Console.WriteLine("}");
   }
}
// The example displays the following output:   
//    {, c, h, a, r, a, c, t, e, r, s, }
Imports System.Text.RegularExpressions

Module Main
   Public Sub Main()
      Dim input As String = "characters"
      Dim regex As New Regex("")
      Dim substrings() As String = regex.Split(input)
      Console.Write("{")
      For ctr As Integer = 0 to substrings.Length - 1
         Console.Write(substrings(ctr))
         If ctr < substrings.Length - 1 Then Console.Write(", ")
      Next
      Console.WriteLine("}")
   End Sub
End Module
' The example produces the following output:   
'    {, c, h, a, r, a, c, t, e, r, s, }

請注意, 傳回的陣列也會在陣列的開頭和結尾包含空字串。Note that the returned array also includes an empty string at the beginning and end of the array.

如果分割作業的執行時間超過由此Regex.Regex(String, RegexOptions, TimeSpan)函式所指定的逾時間隔, 就會擲回例外狀況。RegexMatchTimeoutExceptionThe RegexMatchTimeoutException exception is thrown if the execution time of the split operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

另請參閱

Split(String, String) Split(String, String) Split(String, String) Split(String, String)

在規則運算式模式所定義的位置,將輸入字串分割成子字串陣列。Splits an input string into an array of substrings at the positions defined by a regular expression pattern.

public:
 static cli::array <System::String ^> ^ Split(System::String ^ input, System::String ^ pattern);
public static string[] Split (string input, string pattern);
static member Split : string * string -> string[]
Public Shared Function Split (input As String, pattern As String) As String()

參數

input
String String String String

要分隔的字串。The string to split.

pattern
String String String String

要比對的規則運算式模式。The regular expression pattern to match.

傳回

String[]

字串的陣列。An array of strings.

例外狀況

發生規則運算式剖析錯誤。A regular expression parsing error occurred.

inputpatternnullinput or pattern is null.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

備註

方法與String.Split方法類似, 不同之處在于會Regex.Split在正則運算式所決定的分隔符號 (而不是一組字元) 上分割字串。 Regex.SplitThe Regex.Split methods are similar to the String.Split method, except that Regex.Split splits the string at a delimiter determined by a regular expression instead of a set of characters. input字串會盡可能分割最多次。The input string is split as many times as possible. 如果patterninput字串中找不到, 則傳回值會包含一個元素, 其值為input原始字串。If pattern is not found in the input string, the return value contains one element whose value is the original input string.

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 如需正則運算式的詳細資訊, 請參閱.NET Framework 正則運算式正則運算式語言-快速參考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.

重要

在靜態Split方法的呼叫中使用編譯的正則運算式會自動快取。Compiled regular expressions used in calls to static Split methods are automatically cached. 若要自行管理已編譯之正則運算式的存留期Split , 請使用實例方法。To manage the lifetime of compiled regular expressions yourself, use the instance Split methods.

如果有多個相符專案彼此相鄰, 則會將空字串插入陣列中。If multiple matches are adjacent to one another, an empty string is inserted into the array. 例如, 將字串分割成單一連字號, 會導致傳回的陣列在找到兩個相鄰連字號的位置包含空字串, 如下列程式碼所示。For example, splitting a string on a single hyphen causes the returned array to include an empty string in the position where two adjacent hyphens are found, as the following code shows.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "plum--pear";
      string pattern = "-";            // Split on hyphens
      
      string[] substrings = Regex.Split(input, pattern);
      foreach (string match in substrings)
      {
         Console.WriteLine("'{0}'", match);
      }
   }
}
// The method displays the following output:
//    'plum'
//    ''
//    'pear'      
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "plum--pear"
      Dim pattern As String = "-"          ' Split on hyphens
      
      Dim substrings() As String = Regex.Split(input, pattern)
      For Each match As String In substrings
         Console.WriteLine("'{0}'", match)
      Next
   End Sub  
End Module
' The example displays the following output:
'    'plum'
'    ''
'    'pear'      

如果在輸入字串的開頭或結尾找到相符項, 則會在傳回陣列的開頭或結尾包含空字串。If a match is found at the beginning or the end of the input string, an empty string is included at the beginning or the end of the returned array. 下列範例會使用正則運算式模式\d+ , 將輸入字串分割為數字字元。The following example uses the regular expression pattern \d+ to split an input string on numeric characters. 因為字串的開頭和結尾都是相符的數位字元, 所以傳回陣列的第一個和最後一個元素的String.Empty值是。Because the string begins and ends with matching numeric characters, the value of the first and last element of the returned array is String.Empty.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\d+";
      string input = "123ABCDE456FGHIJKL789MNOPQ012";
      string[] result = Regex.Split(input, pattern);
      for (int ctr = 0; ctr < result.Length; ctr++) {
         Console.Write("'{0}'", result[ctr]);
         if (ctr < result.Length - 1) 
            Console.Write(", ");
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//       '', 'ABCDE', 'FGHIJKL', 'MNOPQ', ''
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\d+"
      Dim input As String = "123ABCDE456FGHIJKL789MNOPQ012"
      Dim result() As String = Regex.Split(input, pattern)
      For ctr As Integer = 0 To result.Length - 1
         Console.Write("'{0}'", result(ctr))
         If ctr < result.Length - 1 Then Console.Write(", ")
      Next
      Console.WriteLine()
   End Sub               
End Module
' The example displays the following output:
'       '', 'ABCDE', 'FGHIJKL', 'MNOPQ', ''

如果在Regex.Split運算式中使用捕捉括弧, 則產生的字串陣列中會包含任何已捕獲的文字。If capturing parentheses are used in a Regex.Split expression, any captured text is included in the resulting string array. 例如, 如果您將字串 "梅紅-梨" (位於捕捉括弧內的連字號) 分割, 則傳回的陣列會包含包含連字號的 string 元素。For example, if you split the string "plum-pear" on a hyphen placed within capturing parentheses, the returned array includes a string element that contains the hyphen.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "plum-pear";
      string pattern = "(-)";

      string[] substrings = Regex.Split(input, pattern);    // Split on hyphens
      foreach (string match in substrings)
      {
         Console.WriteLine("'{0}'", match);
      }
   }
}
// The example displays the following output:
//    'plum'
//    '-'
//    'pear'      
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "plum-pear"
      Dim pattern As String = "(-)" 
      
      Dim substrings() As String = Regex.Split(input, pattern)    ' Split on hyphens.
      For Each match As String In substrings
         Console.WriteLine("'{0}'", match)
      Next
   End Sub
End Module
' The method writes the following to the console:
'    'plum'
'    '-'
'    'pear'      

不過, 當正則運算式模式包含多組捕捉括弧時, 這個方法的行為取決於 .NET Framework 的版本。However, when the regular expression pattern includes multiple sets of capturing parentheses, the behavior of this method depends on the version of the .NET Framework. 在 .NET Framework 1.0 和1.1 中, 如果在第一組捕捉括弧內找不到相符項, 則傳回的陣列中不會包含來自其他捕捉括弧的已捕捉文字。In the .NET Framework 1.0 and 1.1, if a match is not found within the first set of capturing parentheses, captured text from additional capturing parentheses is not included in the returned array. 從 .NET Framework 2.0 開始, 所有已捕捉的文字也會加入至傳回的陣列。Starting with the .NET Framework 2.0, all captured text is also added to the returned array. 例如, 下列程式碼會使用兩組捕捉括弧, 從日期字串中解壓縮日期的專案, 包括日期分隔符號。For example, the following code uses two sets of capturing parentheses to extract the elements of a date, including the date delimiters, from a date string. 第一組捕捉括弧會捕捉連字號, 而第二組則會捕捉正斜線。The first set of capturing parentheses captures the hyphen, and the second set captures the forward slash. 如果範例程式碼是在 .NET Framework 1.0 或1.1 之下編譯並執行, 則會排除斜線字元;如果編譯並在 .NET Framework 2.0 或更新版本下執行, 則會包含它們。If the example code is compiled and run under the .NET Framework 1.0 or 1.1, it excludes the slash characters; if it is compiled and run under the .NET Framework 2.0 or later versions, it includes them.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = @"07/14/2007";   
      string pattern = @"(-)|(/)";

      foreach (string result in Regex.Split(input, pattern)) 
      {
         Console.WriteLine("'{0}'", result);
      }
   }
}
// In .NET 1.0 and 1.1, the method returns an array of
// 3 elements, as follows:
//    '07'
//    '14'
//    '2007'
//
// In .NET 2.0 and later, the method returns an array of
// 5 elements, as follows:
//    '07'
//    '/'
//    '14'
//    '/'
//    '2007' 
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "07/14/2007"   
      Dim pattern As String = "(-)|(/)"
      For Each result As String In Regex.Split(input, pattern) 
         Console.WriteLine("'{0}'", result)
      Next
   End Sub
End Module
' In .NET 1.0 and 1.1, the method returns an array of
' 3 elements, as follows:
'    '07'
'    '14'
'    '2007'
'
' In .NET 2.0 and later, the method returns an array of
' 5 elements, as follows:
'    '07'
'    '/'
'    '14'
'    '/'
'    '2007' 

如果正則運算式可以符合空字串, 會Split將字串分割成單一字元字串的陣列, 因為在每個位置都可以找到空的字串分隔符號。If the regular expression can match the empty string, Split will split the string into an array of single-character strings because the empty string delimiter can be found at every location. 例如:For example:

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "characters";
      string[] substrings = Regex.Split(input, "");
      Console.Write("{");
      for(int ctr = 0; ctr < substrings.Length; ctr++)
      {
         Console.Write("'{0}'", substrings[ctr]);
         if (ctr < substrings.Length - 1)
            Console.Write(", ");
      }
      Console.WriteLine("}");
   }
}
// The example produces the following output:   
//    {'', 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's', ''}
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "characters"
      Dim substrings() As String = Regex.Split(input, "")
      Console.Write("{")
      For ctr As Integer = 0 to substrings.Length - 1
         Console.Write("'{0}'", substrings(ctr))
         If ctr < substrings.Length - 1 Then Console.Write(", ")
      Next
      Console.WriteLine("}")
   End Sub
End Module
' The example produces the following output:   
'    {'', 'c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's', ''}

請注意, 傳回的陣列也會在陣列的開頭和結尾包含空字串。Note that the returned array also includes an empty string at the beginning and end of the array.

如果分割作業的執行時間超出為呼叫方法的應用程式域指定的逾時間隔, 就會擲回例外狀況(exception)。RegexMatchTimeoutExceptionThe RegexMatchTimeoutException exception is thrown if the execution time of the split operation exceeds the time-out interval specified for the application domain in which the method is called. 如果在應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況。If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

給呼叫者的注意事項

這個方法會在與呼叫方法之應用程式域的預設超時值相等的間隔時間之後發生。This method times out after an interval that is equal to the default time-out value of the application domain in which the method is called. 如果未針對應用程式定義域定義逾時值,則使用值 InfiniteMatchTimeout,使方法不會逾時。If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. 在模式比對上分割文字的建議靜態方法是Split(String, String, RegexOptions, TimeSpan), 可讓您設定逾時間隔。The recommended static method for splitting text on a pattern match is Split(String, String, RegexOptions, TimeSpan), which lets you set the time-out interval.

另請參閱

適用於