Regex コンストラクター

定義

Regex クラスの新しいインスタンスを初期化します。

オーバーロード

Regex()

Regex クラスの新しいインスタンスを初期化します。

Regex(String)

指定した正規表現の Regex クラスの新しいインスタンスを初期化します。

Regex(SerializationInfo, StreamingContext)
古い.

シリアル化したデータを使用して、Regex クラスの新しいインスタンスを初期化します。

Regex(String, RegexOptions)

パターンを変更するオプションを使用して、指定した正規表現の Regex クラスの新しいインスタンスを初期化します。

Regex(String, RegexOptions, TimeSpan)

パターンを変更するオプションと、パターン マッチ メソッドがタイムアウトするまでに一致を試みる時間を指定する値を使用して、指定した正規表現の Regex クラスの新しいインスタンスを初期化します。

Regex()

Source:
Regex.cs
Source:
Regex.cs
Source:
Regex.cs

Regex クラスの新しいインスタンスを初期化します。

protected:
 Regex();
protected Regex ();
Protected Sub New ()

注釈

このコンストラクターは保護されていることに注意してください。これは、 クラスから Regex 派生したクラスによってのみ呼び出すことができます。

適用対象

Regex(String)

Source:
Regex.cs
Source:
Regex.cs
Source:
Regex.cs

指定した正規表現の Regex クラスの新しいインスタンスを初期化します。

public:
 Regex(System::String ^ pattern);
public Regex (string pattern);
new System.Text.RegularExpressions.Regex : string -> System.Text.RegularExpressions.Regex
Public Sub New (pattern As String)

パラメーター

pattern
String

一致させる正規表現パターン。

例外

正規表現の解析エラーが発生しました。

patternnullです。

次の例では、このコンストラクターを使用して、文字 "a" または "t" で始まる単語に一致する正規表現をインスタンス化する方法を示します。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b[at]\w+";
      string text = "The threaded application ate up the thread pool as it executed.";
      MatchCollection matches;

      Regex defaultRegex = new Regex(pattern);
      // Get matches of pattern in text
      matches = defaultRegex.Matches(text);
      Console.WriteLine("Parsing '{0}'", text);
      // Iterate matches
      for (int ctr = 0; ctr < matches.Count; ctr++)
         Console.WriteLine("{0}. {1}", ctr, matches[ctr].Value);
   }
}
// The example displays the following output:
//       Parsing 'The threaded application ate up the thread pool as it executed.'
//       0. threaded
//       1. application
//       2. ate
//       3. the
//       4. thread
//       5. as
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b[at]\w+"
      Dim text As String = "The threaded application ate up the thread pool as it executed."
      Dim matches As MatchCollection

      Dim defaultRegex As New Regex(pattern)
      ' Get matches of pattern in text
      matches = defaultRegex.Matches(text)
      Console.WriteLine("Parsing '{0}'", text)
      ' Iterate matches
      For ctr As Integer = 0 to matches.Count - 1
         Console.WriteLine("{0}. {1}", ctr, matches(ctr).Value)
      Next
   End Sub
End Module
' The example displays the following output:
'       Parsing 'The threaded application ate up the thread pool as it executed.'
'       0. threaded
'       1. application
'       2. ate
'       3. the
'       4. thread
'       5. as

既定では比較では大文字と小文字が区別されるため、正規表現パターンはテキストの先頭にある単語 "The" と一致できないことに注意してください。 大文字と小文字を区別しない比較の例については、 コンストラクターを Regex(String, RegexOptions) 参照してください。

注釈

パラメーターは pattern 、一致する文字列をシンボル的に記述する正規表現言語要素で構成されます。 正規表現の詳細については、「 .NET 正規表現 」および「 正規表現言語 - クイック リファレンス」トピックを参照してください

コンストラクターのRegex(String)呼び出しは、 引数の 値が のNoneRegex(String, RegexOptions)コンストラクターを呼び出すことoptionsと同じです。

Regexオブジェクトは不変です。つまり、オブジェクトを作成するときに定義した一致パターンにのみ使用できます。 ただし、再コンパイルせずに何度でも使用できます。

このコンストラクターは、 で pattern定義されているアルファベット文字の大文字と小文字を区別する一致を試みる正規表現オブジェクトをインスタンス化します。 大文字と小文字を区別しない一致の場合は、 コンストラクターを Regex.Regex(String, RegexOptions) 使用します。

注意 (呼び出し元)

このコンストラクターは、 Regex 作成されるアプリケーション ドメインの既定のタイムアウト値を使用する オブジェクトを作成します。 アプリケーション ドメインに対してタイムアウト値が定義されていない場合、 Regex オブジェクトは 値 InfiniteMatchTimeoutを使用します。これにより、操作のタイムアウトが回避されます。オブジェクトを作成するために Regex 推奨されるコンストラクターは です Regex(String, RegexOptions, TimeSpan)。これにより、タイムアウト間隔を設定できます。

こちらもご覧ください

適用対象

Regex(SerializationInfo, StreamingContext)

Source:
Regex.cs
Source:
Regex.cs
Source:
Regex.cs

注意事項

This API supports obsolete formatter-based serialization. It should not be called or extended by application code.

シリアル化したデータを使用して、Regex クラスの新しいインスタンスを初期化します。

protected:
 Regex(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected Regex (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
[System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
protected Regex (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
new System.Text.RegularExpressions.Regex : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Text.RegularExpressions.Regex
[<System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
new System.Text.RegularExpressions.Regex : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Text.RegularExpressions.Regex
Protected Sub New (info As SerializationInfo, context As StreamingContext)

パラメーター

info
SerializationInfo

シリアル化されたパターンと RegexOptions 情報を保持するオブジェクト。

context
StreamingContext

このシリアル化のシリアル化先。 (このパラメーターは使用されません。null を指定してください。)

属性

例外

正規表現の解析エラーが発生しました。

info に含まれているパターンが null です。

info に無効な RegexOptions フラグが含まれています。

適用対象

Regex(String, RegexOptions)

Source:
Regex.cs
Source:
Regex.cs
Source:
Regex.cs

パターンを変更するオプションを使用して、指定した正規表現の Regex クラスの新しいインスタンスを初期化します。

public:
 Regex(System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options);
public Regex (string pattern, System.Text.RegularExpressions.RegexOptions options);
new System.Text.RegularExpressions.Regex : string * System.Text.RegularExpressions.RegexOptions -> System.Text.RegularExpressions.Regex
Public Sub New (pattern As String, options As RegexOptions)

パラメーター

pattern
String

一致させる正規表現パターン。

options
RegexOptions

正規表現を変更する列挙値のビットごとの組み合わせ。

例外

正規表現の解析エラーが発生しました。

patternnullです。

options に無効なフラグが含まれています。

次の例では、このコンストラクターを使用して、文字 "a" または "t" で始まる単語に一致する正規表現をインスタンス化する方法を示します。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b[at]\w+";
      RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled;
      string text = "The threaded application ate up the thread pool as it executed.";
      MatchCollection matches;

      Regex optionRegex = new Regex(pattern, options);
      Console.WriteLine("Parsing '{0}' with options {1}:", text, options.ToString());
      // Get matches of pattern in text
      matches = optionRegex.Matches(text);
      // Iterate matches
      for (int ctr = 0; ctr < matches.Count; ctr++)
         Console.WriteLine("{0}. {1}", ctr, matches[ctr].Value);
   }
}
// The example displays the following output:
//    Parsing 'The threaded application ate up the thread pool as it executed.'
//        with options IgnoreCase, Compiled:
//    0. The
//    1. threaded
//    2. application
//    3. ate
//    4. the
//    5. thread
//    6. as
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b[at]\w+"
      Dim options As RegexOptions = RegexOptions.IgnoreCase Or RegexOptions.Compiled
      Dim text As String = "The threaded application ate up the thread pool as it executed."
      Dim matches As MatchCollection

      Dim optionRegex As New Regex(pattern, options)
      Console.WriteLine("Parsing '{0}' with options {1}:", text, options.ToString())
      ' Get matches of pattern in text
      matches = optionRegex.Matches(text)
      ' Iterate matches   
      For ctr As Integer = 0 to matches.Count - 1
         Console.WriteLine("{0}. {1}", ctr, matches(ctr).Value)
      Next
   End Sub
End Module
' The example displays the following output:
'    Parsing 'The threaded application ate up the thread pool as it executed.'
'       with options IgnoreCase, Compiled:
'    0. The
'    1. threaded
'    2. application
'    3. ate
'    4. the
'    5. thread
'    6. as

match コレクションには、パラメーターで大文字と小文字を区別しない比較が定義されているため、テキストを options 開始する単語 "The" が含まれていることに注意してください。

注釈

パラメーターは pattern 、一致する文字列をシンボル的に記述する正規表現言語要素で構成されます。 正規表現の詳細については、「 .NET 正規表現 」および「 正規表現言語 - クイック リファレンス」トピックを参照してください

Regexオブジェクトは不変です。つまり、オブジェクトを作成するときに定義した一致パラメーターにのみ使用できます。 ただし、再コンパイルせずに何度でも使用できます。

注意 (呼び出し元)

このコンストラクターは、 Regex 作成されるアプリケーション ドメインの既定のタイムアウト値を使用する オブジェクトを作成します。 アプリケーション ドメインに対してタイムアウト値が定義されていない場合、 Regex オブジェクトは 値 InfiniteMatchTimeoutを使用します。これにより、操作のタイムアウトが回避されます。オブジェクトを作成するために Regex 推奨されるコンストラクターは です Regex(String, RegexOptions, TimeSpan)。これにより、タイムアウト間隔を設定できます。

こちらもご覧ください

適用対象

Regex(String, RegexOptions, TimeSpan)

Source:
Regex.cs
Source:
Regex.cs
Source:
Regex.cs

パターンを変更するオプションと、パターン マッチ メソッドがタイムアウトするまでに一致を試みる時間を指定する値を使用して、指定した正規表現の Regex クラスの新しいインスタンスを初期化します。

public:
 Regex(System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public Regex (string pattern, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
new System.Text.RegularExpressions.Regex : string * System.Text.RegularExpressions.RegexOptions * TimeSpan -> System.Text.RegularExpressions.Regex
Public Sub New (pattern As String, options As RegexOptions, matchTimeout As TimeSpan)

パラメーター

pattern
String

一致させる正規表現パターン。

options
RegexOptions

正規表現を変更する列挙値のビットごとの組み合わせ。

matchTimeout
TimeSpan

タイムアウト期間、またはメソッドがタイムアウトしないことを示す InfiniteMatchTimeout

例外

正規表現の解析エラーが発生しました。

patternnullです。

options は有効な RegexOptions 値ではありません。

- または -

matchTimeout が負の値か、0 か、または約 24 日を超えています。

次の例では、 コンストラクターを Regex(String, RegexOptions, TimeSpan) 呼び出して、 Regex タイムアウト値が 1 秒のオブジェクトをインスタンス化します。 正規表現パターン (a+)+$ は、行の末尾にある 1 つ以上の "a" 文字の 1 つ以上のシーケンスに一致しますが、過度なバックトラッキングの対象になります。 RegexMatchTimeoutExceptionがスローされた場合、タイムアウト値を最大値の 3 秒まで増やします。 それ以外の場合は、パターンに一致する試行を破棄します。

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Security;
using System.Text.RegularExpressions;
using System.Threading; 

public class Example
{
   const int MaxTimeoutInSeconds = 3;

   public static void Main()
   {
      string pattern = @"(a+)+$";    // DO NOT REUSE THIS PATTERN.
      Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));       
      Stopwatch sw = null;
      
      string[] inputs= { "aa", "aaaa>", 
                         "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                         "aaaaaaaaaaaaaaaaaaaaaa>",
                         "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>" };
                                 
      foreach (var inputValue in inputs) {
         Console.WriteLine("Processing {0}", inputValue);
         bool timedOut = false;
         do { 
            try {
               sw = Stopwatch.StartNew();
               // Display the result.
               if (rgx.IsMatch(inputValue)) {
                  sw.Stop();
                  Console.WriteLine(@"Valid: '{0}' ({1:ss\.fffffff} seconds)", 
                                    inputValue, sw.Elapsed); 
               }
               else {
                  sw.Stop();
                  Console.WriteLine(@"'{0}' is not a valid string. ({1:ss\.fffff} seconds)", 
                                    inputValue, sw.Elapsed);
               }
            }
            catch (RegexMatchTimeoutException e) {   
               sw.Stop();
               // Display the elapsed time until the exception.
               Console.WriteLine(@"Timeout with '{0}' after {1:ss\.fffff}", 
                                 inputValue, sw.Elapsed);
               Thread.Sleep(1500);       // Pause for 1.5 seconds.

               // Increase the timeout interval and retry.
               TimeSpan timeout = e.MatchTimeout.Add(TimeSpan.FromSeconds(1));
               if (timeout.TotalSeconds > MaxTimeoutInSeconds) {
                  Console.WriteLine("Maximum timeout interval of {0} seconds exceeded.",
                                    MaxTimeoutInSeconds);
                  timedOut = false;
               }
               else {               
                  Console.WriteLine("Changing the timeout interval to {0}", 
                                    timeout); 
                  rgx = new Regex(pattern, RegexOptions.IgnoreCase, timeout);
                  timedOut = true;
               }
            }
         } while (timedOut);
         Console.WriteLine();
      }   
   }
}
// The example displays output like the following :
//    Processing aa
//    Valid: 'aa' (00.0000779 seconds)
//    
//    Processing aaaa>
//    'aaaa>' is not a valid string. (00.00005 seconds)
//    
//    Processing aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
//    Valid: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' (00.0000043 seconds)
//    
//    Processing aaaaaaaaaaaaaaaaaaaaaa>
//    Timeout with 'aaaaaaaaaaaaaaaaaaaaaa>' after 01.00469
//    Changing the timeout interval to 00:00:02
//    Timeout with 'aaaaaaaaaaaaaaaaaaaaaa>' after 02.01202
//    Changing the timeout interval to 00:00:03
//    Timeout with 'aaaaaaaaaaaaaaaaaaaaaa>' after 03.01043
//    Maximum timeout interval of 3 seconds exceeded.
//    
//    Processing aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>
//    Timeout with 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>' after 03.01018
//    Maximum timeout interval of 3 seconds exceeded.
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Security
Imports System.Text.RegularExpressions
Imports System.Threading 

Module Example
   Const MaxTimeoutInSeconds As Integer = 3
   
   Public Sub Main()
      Dim pattern As String = "(a+)+$"    ' DO NOT REUSE THIS PATTERN.
      Dim rgx As New Regex(pattern, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1))       
      Dim sw As Stopwatch = Nothing
      
      Dim inputs() As String = { "aa", "aaaa>", 
                                 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                                 "aaaaaaaaaaaaaaaaaaaaaa>",
                                 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>" }
                                 
      For Each inputValue In inputs
         Console.WriteLine("Processing {0}", inputValue)
         Dim timedOut As Boolean = False
         Do 
            Try
               sw = Stopwatch.StartNew()
               ' Display the result.
               If rgx.IsMatch(inputValue) Then
                  sw.Stop()
                  Console.WriteLine("Valid: '{0}' ({1:ss\.fffffff} seconds)", 
                                    inputValue, sw.Elapsed) 
               Else
                  sw.Stop()
                  Console.WriteLine("'{0}' is not a valid string. ({1:ss\.fffff} seconds)", 
                                    inputValue, sw.Elapsed)
               End If
            Catch e As RegexMatchTimeoutException   
               sw.Stop()
               ' Display the elapsed time until the exception.
               Console.WriteLine("Timeout with '{0}' after {1:ss\.fffff}", 
                                 inputValue, sw.Elapsed)
               Thread.Sleep(1500)       ' Pause for 1.5 seconds.

               ' Increase the timeout interval and retry.
               Dim timeout As TimeSpan = e.MatchTimeout.Add(TimeSpan.FromSeconds(1))
               If timeout.TotalSeconds > MaxTimeoutInSeconds Then
                  Console.WriteLine("Maximum timeout interval of {0} seconds exceeded.",
                                    MaxTimeoutInSeconds)
                  timedOut = False
               Else                
                  Console.WriteLine("Changing the timeout interval to {0}", 
                                    timeout) 
                  rgx = New Regex(pattern, RegexOptions.IgnoreCase, timeout)
                  timedOut = True
               End If
            End Try
         Loop While timedOut
         Console.WriteLine()
      Next   
   End Sub 
End Module
' The example displays output like the following:
'    Processing aa
'    Valid: 'aa' (00.0000779 seconds)
'    
'    Processing aaaa>
'    'aaaa>' is not a valid string. (00.00005 seconds)
'    
'    Processing aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
'    Valid: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' (00.0000043 seconds)
'    
'    Processing aaaaaaaaaaaaaaaaaaaaaa>
'    Timeout with 'aaaaaaaaaaaaaaaaaaaaaa>' after 01.00469
'    Changing the timeout interval to 00:00:02
'    Timeout with 'aaaaaaaaaaaaaaaaaaaaaa>' after 02.01202
'    Changing the timeout interval to 00:00:03
'    Timeout with 'aaaaaaaaaaaaaaaaaaaaaa>' after 03.01043
'    Maximum timeout interval of 3 seconds exceeded.
'    
'    Processing aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>
'    Timeout with 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>' after 03.01018
'    Maximum timeout interval of 3 seconds exceeded.

注釈

パラメーターは pattern 、一致する文字列をシンボル的に記述する正規表現言語要素で構成されます。 正規表現の詳細については、「 .NET 正規表現 」および「 正規表現言語 - クイック リファレンス」トピックを参照してください

Regexオブジェクトは不変です。つまり、オブジェクトを作成するときに定義した一致パターンにのみ使用できます。 ただし、再コンパイルせずに何度でも使用できます。

パラメーターは matchTimeout 、パターン マッチング メソッドがタイムアウトするまでに一致を検索する期間を指定します。その時間間隔で一致するものが見つからない場合、パターンマッチングメソッドは例外を RegexMatchTimeoutException スローします。 matchTimeout は、オブジェクトが作成されるアプリケーション ドメインに定義されている既定のタイムアウト値を Regex オーバーライドします。 タイムアウト間隔を観察 matchTimeout するインスタンス パターンマッチング メソッドには、次のものがあります。

タイムアウト間隔を設定すると、過剰なバックトラッキングに依存する正規表現が、近い一致を含む入力を処理するときに応答を停止するように見えなくなります。 詳細については、「正規表現とバックトラッキングのベスト プラクティス」を参照してください。 適切なタイムアウト間隔を設定するには、次の要因を考慮してください。

  • 正規表現パターンの長さと複雑さ。 より長く複雑な正規表現では、短くシンプルな正規表現よりも多くの時間が必要です。

  • 予想されるマシンの負荷。 CPU とメモリの使用率が高いシステムでは、処理に時間がかかります。

注意 (呼び出し元)

パラメーターを適切な値 (2 秒など) に設定 matchTimeout することをお勧めします。 を指定してタイムアウトを InfiniteMatchTimeout無効にすると、正規表現エンジンのパフォーマンスが若干向上します。 ただし、タイムアウトは次の条件でのみ無効にする必要があります。

  • 正規表現によって処理される入力が既知の信頼できるソースから派生した場合、または静的テキストで構成されている場合。 これにより、ユーザーによって動的に入力されたテキストが除外されます。

  • 正規表現パターンが十分にテストされ、一致、一致しない、近い一致が効率的に処理されるようにする場合。

  • 正規表現パターンに、近い一致を処理するときに過剰なバックトラッキングを引き起こすことがわかっている言語要素が含まれない場合。

こちらもご覧ください

適用対象