C#-正規表現
A regular expression入力テキストと照合できるパターンです。.Net Frameworkは、そのようなマッチングを可能にする正規表現エンジンを提供します。パターンは、1つ以上の文字リテラル、演算子、または構成で構成されます。
正規表現を定義するための構成
正規表現を定義できる文字、演算子、および構成のさまざまなカテゴリがあります。これらの構成を見つけるには、次のリンクをクリックしてください。
文字エスケープ
キャラクタークラス
Anchors
グループ化構造
Quantifiers
後方参照構造
交替構成
Substitutions
その他の構成
正規表現クラス
Regexクラスは、正規表現を表すために使用されます。以下の一般的に使用される方法があります-
シニア番号 | 方法と説明 |
---|---|
1 | public bool IsMatch(string input) Regexコンストラクターで指定された正規表現が、指定された入力文字列で一致を見つけるかどうかを示します。 |
2 | public bool IsMatch(string input, int startat) Regexコンストラクターで指定された正規表現が、文字列の指定された開始位置から開始して、指定された入力文字列で一致を見つけるかどうかを示します。 |
3 | public static bool IsMatch(string input, string pattern) 指定された正規表現が指定された入力文字列で一致を見つけるかどうかを示します。 |
4 | public MatchCollection Matches(string input) 指定された入力文字列で、正規表現のすべての出現箇所を検索します。 |
5 | public string Replace(string input, string replacement) 指定された入力文字列で、正規表現パターンに一致するすべての文字列を指定された置換文字列に置き換えます。 |
6 | public string[] Split(string input) Regexコンストラクターで指定された正規表現パターンによって定義された位置で、入力文字列を部分文字列の配列に分割します。 |
メソッドとプロパティの完全なリストについては、C#に関するMicrosoftのドキュメントをお読みください。
例1
次の例は、「S」で始まる単語に一致します。
using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
class Program {
private static void showMatch(string text, string expr) {
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc) {
Console.WriteLine(m);
}
}
static void Main(string[] args) {
string str = "A Thousand Splendid Suns";
Console.WriteLine("Matching words that start with 'S': ");
showMatch(str, @"\bS\S*");
Console.ReadKey();
}
}
}
上記のコードをコンパイルして実行すると、次の結果が得られます。
Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns
例2
次の例は、「m」で始まり「e」で終わる単語に一致します。
using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
class Program {
private static void showMatch(string text, string expr) {
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc) {
Console.WriteLine(m);
}
}
static void Main(string[] args) {
string str = "make maze and manage to measure it";
Console.WriteLine("Matching words start with 'm' and ends with 'e':");
showMatch(str, @"\bm\S*e\b");
Console.ReadKey();
}
}
}
上記のコードをコンパイルして実行すると、次の結果が得られます。
Matching words start with 'm' and ends with 'e':
The Expression: \bm\S*e\b
make
maze
manage
measure
例3
この例は余分な空白を置き換えます-
using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
class Program {
static void Main(string[] args) {
string input = "Hello World ";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
Console.ReadKey();
}
}
}
上記のコードをコンパイルして実行すると、次の結果が得られます。
Original String: Hello World
Replacement String: Hello World