Regex クラス
アセンブリ: System (system.dll 内)


Regex クラスには、Regex オブジェクトを明示的に作成しなくても正規表現を使用できるようにする静的メソッドがいくつかあります。静的メソッドを使用することは、Regex オブジェクトを構築し、一度使用してから破棄することと等しい操作になります。
Regex クラスは変更不可 (読み取り専用) でスレッド セーフになっています。Regex オブジェクトはどのスレッドにでも作成でき、複数のスレッド間で共有できます。詳細については、「スレッド セーフ」を参照してください。

正規表現を使用して、文字列が通貨値を表す正しい形式かどうかをチェックするコード例を次に示します。^ および $ トークンで囲むことにより、部分文字列ではなく文字列全体が正規表現に一致する必要があることを示している点に注意してください。
using System; using System.Text.RegularExpressions; public class Test { public static void Main () { // Define a regular expression for currency values. Regex rx = new Regex(@"^-?\d+(\.\d{2})?$"); // Define some test strings. string[] tests = {"-42", "19.99", "0.001", "100 USD"}; // Check each test string against the regular expression. foreach (string test in tests) { if (rx.IsMatch(test)) { Console.WriteLine("{0} is a currency value.", test); } else { Console.WriteLine("{0} is not a currency value.", test); } } } }
#using <System.dll> using namespace System; using namespace System::Text::RegularExpressions; int main() { // Define a regular expression for currency values. Regex^ rx = gcnew Regex( "^-?\\d+(\\.\\d{2})?$" ); // Define some test strings. array<String^>^tests = {"-42","19.99","0.001","100 USD"}; // Check each test string against the regular expression. System::Collections::IEnumerator^ myEnum = tests->GetEnumerator(); while ( myEnum->MoveNext() ) { String^ test = safe_cast<String^>(myEnum->Current); if ( rx->IsMatch( test ) ) { Console::WriteLine( "{0} is a currency value.", test ); } else { Console::WriteLine( "{0} is not a currency value.", test ); } } }
import System.*; import System.Text.RegularExpressions.*; public class Test { public static void main(String[] args) { // Define a regular expression for currency values. Regex rx = new Regex("^-?\\d+(\\.\\d{2})?$"); // Define some test strings. String tests[] = { "-42", "19.99", "0.001", "100 USD" }; // Check each test string against the regular expression. for (int iCtr = 0; iCtr < tests.get_Length(); iCtr++) { String test = (String)tests.get_Item(iCtr); if (rx.IsMatch(test)) { Console.WriteLine("{0} is a currency value.", test); } else { Console.WriteLine("{0} is not a currency value.", test); } } } //main } //Test
正規表現を使用して、文字列内で繰り返し出現する語をチェックするコード例を次に示します。(?<word>) 構成体を使用してグループに名前を付け、(\k<word>) 構成体を使用してそのグループを式内で後から参照していることに注意してください。
using System; using System.Text.RegularExpressions; public class Test { public static void Main () { // Define a regular expression for repeated words. Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b" , RegexOptions.Compiled | RegexOptions.IgnoreCase); // Define a test string. string text = "The the quick brown fox fox jumped over the lazy dog dog."; // Find matches. MatchCollection matches = rx.Matches(text); // Report the number of matches found. Console.WriteLine("{0} matches found.", matches.Count); // Report on each match. foreach (Match match in matches) { string word = match.Groups["word"].Value; int index = match.Index; Console.WriteLine("{0} repeated at position {1}", word, index); } } }
#using <System.dll> using namespace System; using namespace System::Text::RegularExpressions; int main() { // Define a regular expression for repeated words. Regex^ rx = gcnew Regex( "\\b(?<word>\\w+)\\s+(\\k<word>)\\b",static_cast<RegexOptions>(RegexOptions::Compiled | RegexOptions::IgnoreCase) ); // Define a test string. String^ text = "The the quick brown fox fox jumped over the lazy dog dog."; // Find matches. MatchCollection^ matches = rx->Matches( text ); // Report the number of matches found. Console::WriteLine( "{0} matches found.", matches->Count ); // Report on each match. for each (Match^ match in matches) { String^ word = match->Groups["word"]->Value; int index = match->Index; Console::WriteLine("{0} repeated at position {1}", word, index); } }
import System.*; import System.Text.RegularExpressions.*; public class Test { public static void main(String[] args) { // Define a regular expression for repeated words. Regex rx = new Regex("\\b(?<word>\\w+)\\s+(\\k<word>)\\b", RegexOptions.Compiled | RegexOptions.IgnoreCase); // Define a test string. String text = "The the quick brown fox fox jumped over the " + "lazy dog dog."; // Find matches. MatchCollection matches = rx.Matches(text); // Report the number of matches found. Console.WriteLine("{0} matches found.", (Int32)matches.get_Count()); // Report on each match. for (int iCtr = 0; iCtr < matches.get_Count(); iCtr++) { Match match = matches.get_Item(iCtr); String word = match.get_Groups().get_Item("word").get_Value(); int index = match.get_Index(); Console.WriteLine("{0} repeated at position {1}", word, (Int32)index); } } //main } //Test



Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


Regex コンストラクタ ()
アセンブリ: System (system.dll 内)


Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


Regex コンストラクタ (String)
アセンブリ: System (system.dll 内)



pattern パラメータは、一致する文字列をシンボルで表すさまざまな正規表現言語要素で構成されています。正規表現の詳細については、「.NET Framework の正規表現」および「正規表現言語要素」を参照してください。
Regex オブジェクトは変更不可であるため、そのオブジェクトの作成時に定義された一致パラメータに対してしか使用できません。しかし、再コンパイルせずに何度でも使用できます。

このコンストラクタを使用し、正規表現を指定されたパターンでインスタンス化するコード例を次に示します。^ および $ トークンで囲むことにより、部分文字列ではなく文字列全体が正規表現に一致する必要があることを示している点に注意してください。
// Define a regular expression for currency values. Regex^ rx = gcnew Regex( "^-?\\d+(\\.\\d{2})?$" );

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


Regex コンストラクタ (String, RegexOptions)
アセンブリ: System (system.dll 内)



pattern パラメータは、一致する文字列をシンボルで表すさまざまな正規表現言語要素で構成されています。正規表現の詳細については、「.NET Framework の正規表現」および「正規表現言語要素」を参照してください。
Regex オブジェクトは変更不可であるため、そのオブジェクトの作成時に定義された一致パラメータに対してしか使用できません。しかし、再コンパイルせずに何度でも使用できます。

このコンストラクタを使用し、パターンおよびオプションを指定して正規表現をインスタンス化するコード例を次に示します。
// Define a regular expression for repeated words. Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b" , RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Define a regular expression for repeated words. Regex^ rx = gcnew Regex( "\\b(?<word>\\w+)\\s+(\\k<word>)\\b",static_cast<RegexOptions>(RegexOptions::Compiled | RegexOptions::IgnoreCase) );

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


Regex コンストラクタ (SerializationInfo, StreamingContext)
アセンブリ: System (system.dll 内)

Dim info As SerializationInfo Dim context As StreamingContext Dim instance As New Regex(info, context)


Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


Regex コンストラクタ

名前 | 説明 |
---|---|
Regex () | Regex クラスの新しいインスタンスを初期化します。 .NET Compact Framework によってサポートされています。 |
Regex (String) | 指定した正規表現の Regex クラスの新しいインスタンスを初期化およびコンパイルします。 .NET Compact Framework によってサポートされています。 |
Regex (SerializationInfo, StreamingContext) | シリアル化したデータを使用して、Regex クラスの新しいインスタンスを初期化します。 |
Regex (String, RegexOptions) | パターンを変更するオプションを使用して、指定した正規表現の Regex クラスの新しいインスタンスを初期化およびコンパイルします。 .NET Compact Framework によってサポートされています。 |

Regex フィールド

名前 | 説明 | |
---|---|---|
![]() | capnames | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |
![]() | caps | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |
![]() | capsize | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |
![]() | capslist | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |
![]() | pattern | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |
![]() | roptions | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |

Regex プロパティ
Regex メソッド


名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 ( Object から継承されます。) |
![]() | InitializeReferences | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |
![]() | MemberwiseClone | 現在の Object の簡易コピーを作成します。 ( Object から継承されます。) |
![]() | UseOptionC | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |
![]() | UseOptionR | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |

名前 | 説明 | |
---|---|---|
![]() | System.Runtime.Serialization.ISerializable.GetObjectData | SerializationInfo オブジェクトに、現在の Regex オブジェクトの逆シリアル化に必要なデータを入力します。 |

Regex メンバ
Regex データ型で公開されるメンバを以下の表に示します。



名前 | 説明 | |
---|---|---|
![]() | capnames | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |
![]() | caps | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |
![]() | capsize | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |
![]() | capslist | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |
![]() | pattern | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |
![]() | roptions | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |



名前 | 説明 | |
---|---|---|
![]() | Finalize | Object がガベージ コレクションにより収集される前に、その Object がリソースを解放し、その他のクリーンアップ操作を実行できるようにします。 (Object から継承されます。) |
![]() | InitializeReferences | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |
![]() | MemberwiseClone | 現在の Object の簡易コピーを作成します。 (Object から継承されます。) |
![]() | UseOptionC | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |
![]() | UseOptionR | CompileToAssembly メソッドで生成される Regex オブジェクトによって使用されます。 |

名前 | 説明 | |
---|---|---|
![]() | System.Runtime.Serialization.ISerializable.GetObjectData | SerializationInfo オブジェクトに、現在の Regex オブジェクトの逆シリアル化に必要なデータを入力します。 |

正規表現
![]() | 出典は列挙するだけでなく、脚注などを用いてどの記述の情報源であるかを明記してください。 |
正規表現(せいきひょうげん、英: regular expression)は、文字列の集合を一つの文字列で表現する方法の一つである。
もともと正規表現は形式言語理論において正規言語を表すための手段として導入された。形式言語理論では、形式言語が「正規言語であること」と「正規表現によって表せること」は同値である。
その後正規表現は単機能の文字列探索ツールやテキストエディタ、ワードプロセッサなどのアプリケーションで、マッチさせるべき対象を表すために使用されるようになり、表せるパターンの種類を増やすために本来の正規表現にはないさまざまな記法が新たに付け加えられた。このような拡張された正規表現には正規言語ではない文字列も表せるものも多く、ゆえに正規表現という名前は実態に即していない面もあるが、伝統的に正規表現と呼ばれ続けている。
この記事では主にこのような正規表現を用いたパターンマッチングについて説明している。以下、誤解のない限り、アプリケーションやプログラミングにおいて正規表現を用いた文字列のパターンマッチングを行う機能のことを、単に正規表現という。
ほとんどのプログラミング言語では、ライブラリによって正規表現を使うことができる他、一部の言語では正規表現のリテラルもある。「正規表現によるマッチ」を意味する(専用の)演算子がある言語なども一部ある。具体例として、grep, AWK, sed, Perl, Tcl, lex などがある。
それぞれの言語やアプリケーションで細部の仕様が異なっている、といったように思われることも多いが(古い実装では実際にそのようなことも多い)、近年は同じライブラリを使っていれば同じということも多い。またPOSIXなど標準もある。
基本的な概念
理論的に明解であり扱いも容易であるため、形式的な説明を先に述べる。
形式的な説明
記号(アルファベット)
- Jeffrey E.F. Friedl『詳説正規表現』歌代和正監訳、春遍雀來・鈴木武生共訳(第1版)、オライリー・ジャパン、1999年4月。ISBN 4-900900-45-1。
- Jeffrey E.F. Friedl『詳説正規表現』田和勝訳(第2版)、オライリー・ジャパン、2003年5月。ISBN 4-87311-130-7。
- Jeffrey E.F. Friedl『詳説正規表現』株式会社ロングテール・長尾高弘訳(第3版)、オライリー・ジャパン、2008年4月。ISBN 978-4-87311-359-3 。
- Jan Goyvaerts、Steven Levithan『正規表現クックブック』長尾高弘訳、オライリー・ジャパン、2010年4月。ISBN 978-4-87311-450-7 。
外部リンク
- 正規表現 - MDN (MDN Web Docs) ・(翻訳版)
- 正規表現メモ - sed, grep, perl など様々なソフトの正規表現がまとめられている。
- regexのページへのリンク