ページ 11

C# 正規表現 大かっこ

Posted: 2011年11月03日(木) 23:30
by
こんにちは。

現在C#で正規表現を使い、2つの特定の文字列の間にある文字列を取得するプログラムを組んでいます。

コード:

using System.Text.RegularExpressions;

/*--省略--*/

string str = "aaabccccc";      //  元の文字列

Regex reg = new Regex("aaa(?<text>.*?)cc",    //  ここでは「b」がtextに入る
    RegexOptions.IgnoreCase | RegexOptions.Singleline);

string value = "";

for (Match m = reg.Match(str); m.Success; m = m.NextMatch())
{
    value = m.Groups["text"].Value;
    MessageBox.Show(value);    //  出力:b
}

/*--省略--*/
これは普通に動くのですが、


コード:

using System.Text.RegularExpressions;

/*--省略--*/

string str = "aaa[b]";      //  元の文字列

Regex reg = new Regex("aaa[(?<text>.*?)]",    //  ここでは「b」がtextに入るはず
    RegexOptions.IgnoreCase | RegexOptions.Singleline);

string value = "";

for (Match m = reg.Match(str); m.Success; m = m.NextMatch())
{
    value = m.Groups["text"].Value;
    MessageBox.Show(value);
}

/*--省略--*/
こう元の文字列に大かっこが入ると出力してくれません。

これはどういう理由でこうなるのでしょう?
また、解決策はあるのでしょうか?

宜しくお願いします。

Re: C# 正規表現 大かっこ

Posted: 2011年11月03日(木) 23:45
by a5ua
[はエスケープする必要があります。

コード:

new Regex("aaa\\[(?<text>.*?)\\]", ...
もしくは

コード:

new Regex(@"aaa\[(?<text>.*?)\]", ...
としてはどうでしょうか。

Re: C# 正規表現 大かっこ

Posted: 2011年11月04日(金) 00:10
by
返信ありがとうございます。解決いたしました!

大括弧は特殊な文字列だったのですね;

ありがとうございました。