.NETで正規表現ライブラリを使う

最終更新日

Comment: 1

前回のboostの正規表現ライブラリのサンプルに引き続き、C#とC++/CLI、VB.NETでも同じサンプルを書いてみました。全て.NET FrameworkのSystem.Text.RegularExpressions.Regexを用いています。

なんてことはありませんね。

C#版

こちらはMono 2.6.7環境のmcs/gmcsでビルドしてチェックしました。

[csharp]
using System;
using System.Text.RegularExpressions;

// usage: a.exe pattern replace-to

public class Program
{
static int Main(string[] v)
{
if (v.Length != 2) return 1;

Regex r = new Regex(v[0]); // 正規表現オブジェクト
string buf;                // 読み取り用のバッファ

while ((buf = Console.ReadLine()) != null)
  Console.WriteLine(r.Replace(buf, v[1]));

return 0;

}
}
[/csharp]

C++/CLI版

C++/CLIはオープンソースなコンパイラが存在しないため、Microsoft Visual Studio 2008 SP1を用いてビルド、チェックしました。

[cpp]
using namespace System;
using namespace System::Text::RegularExpressions;

// usage: a.exe pattern replace-to

int main(array<System::String ^> ^v)
{
if (v->Length != 2) return 1;

Regex^ r = gcnew Regex(v[0]); // 正規表現オブジェクト
String^ buf;                  // 読み取り用のバッファ

while ((buf = Console::ReadLine()) != nullptr)
    Console::WriteLine(r-&gt;Replace(buf, v[1]));

return 0;

}
[/cpp]

VB.NET版

ついでにVB.NET版も。これもMonoのvbncでテストしました。

[vb]
Imports System
Imports System.Text.RegularExpressions

Module Program

Public Sub Main(ByVal v() As String)

If v.Length &lt;&gt; 2 Then Exit Sub

Dim r As New Regex(v(0)) ' 正規表現オブジェクト
Dim buf As String        ' 読み取り用のバッファ
buf = Console.ReadLine() ' 代入結合判定できないので
                         ' 予め内容を詰めておく。

While buf &lt;&gt; Nothing
  Console.WriteLine(r.Replace(buf, v(1)))
  buf = Console.ReadLine()
End While

End Sub

End Module
[/vb]

佐世保のシステムエンジニアです。詳しいプロフィールやこのブログについてはこちらをご覧ください。

1件のコメント

Bash, Perl, Ruby, Pythonで正規表現置換 | dyama's home page へ返信する コメントをキャンセル

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

コメントする

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください