C# Language
正規表現の解析
サーチ…
構文
-
new Regex(pattern);// 定義されたパターンで新しいインスタンスを作成します。 -
Regex.Match(input);// ルックアップを開始し、Matchを返します。 -
Regex.Matches(input);// 検索を開始し、MatchCollectionを返します。
パラメーター
| 名 | 詳細 |
|---|---|
| パターン | ルックアップに使用するstringパターン。詳細情報: msdn |
| RegexOptions [オプション] | ここでの一般的なオプションはSinglelineとMultilineです。 Multiline-Mode SingleLine-Mode Multiline-Modeなく、 SingleLine-Mode Multiline-ModeでのNewLine (\ n)をカバーしないドット(。)のようなパターン要素の動作を変更していSingleLine-Mode 。既定の動作: msdn |
| タイムアウト[オプション] | パターンがより複雑になるところでは、参照はより多くの時間を消費する可能性があります。これは、ネットワークプログラミングで知られているように、ルックアップに渡されたタイムアウトです。 |
備考
使用する必要があります
using System.Text.RegularExpressions;
いいね
- ここで結果を得るためにソリューションをコンパイルする必要なく、パターンをオンラインでテストできます: Click me
- Regex101例: 私をクリックしてください
初心者は、パワフルで、複雑なテキストベースの検索のための適切な場所にいるため、正規表現で作業を過度にする傾向があります。これは、 XmlDocumentようなこのタスクのために既に完成したクラスが存在する可能性があるかどうかを尋ねることなしに、人々が正規表現でXML文書を解析しようとするポイントXmlDocument 。
正規表現は複雑さを取り除く最後の武器でなければなりません。少なくとも20行のパターンを書き留める前にright wayを探す努力を忘れることは少なくともありません。
シングルマッチ
using System.Text.RegularExpressions;
string pattern = ":(.*?):";
string lookup = "--:text in here:--";
// Instanciate your regex object and pass a pattern to it
Regex rgxLookup = new Regex(pattern, RegexOptions.Singleline, TimeSpan.FromSeconds(1));
// Get the match from your regex-object
Match mLookup = rgxLookup.Match(lookup);
// The group-index 0 always covers the full pattern.
// Matches inside parentheses will be accessed through the index 1 and above.
string found = mLookup.Groups[1].Value;
結果:
found = "text in here"
複数の一致
using System.Text.RegularExpressions;
List<string> found = new List<string>();
string pattern = ":(.*?):";
string lookup = "--:text in here:--:another one:-:third one:---!123:fourth:";
// Instanciate your regex object and pass a pattern to it
Regex rgxLookup = new Regex(pattern, RegexOptions.Singleline, TimeSpan.FromSeconds(1));
MatchCollection mLookup = rgxLookup.Matches(lookup);
foreach(Match match in mLookup)
{
found.Add(match.Groups[1].Value);
}
結果:
found = new List<string>() { "text in here", "another one", "third one", "fourth" }
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow