正規表現の使い方
正規表現とは、文字列を検索するときに使うパターンのことです。正規表現をある文章に対してマッチさせて、検索したいものがあれば成功。無ければ失敗になります。あるときは成功したか失敗したか分かれば十分でしょう。またあるときは、検索した文字列を置換することもできます。System.Text.RegularExpressions.Regexを使う
.NET Frameworkで正規表現を使うには、Regexクラスを使います。Regexクラスを使う準備は次のように行います。from System.Text.RegularExpressions import *
後でMach、Groupクラスなども使えるように最後を"*"にしておくと便利です。It is rather for us to be here dedicated to the great task remaining before us -- that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion -- that we here highly resolve that these dead shall not have died in vain -- that this nation, under God, shall have a new birth of freedom -- and that government of the people, by the people, for the people, shall not perish from the earth.
上記はリンカーン大統領の有名な演説です。その中でも特に有名な下線部の文節を使って、Regexで遊んでみましょう。
word = "and that government of the people, by the people, for the
people,"
pattern = "people"
上記のように検索される対象の文字列をword、検索する文字列をpatternとしました。これらを使って説明します。正規表現の詳細は.NET Frameworkで使える正規表現で説明します。
IsMatchメゾット
Regex.IsMatch(Str, Pattern)
patternで指定された正規表現を使用して、その正規表現と一致する対象がStr文字列内に見つかったかどうかを示します。 返り値はbool値でTrue,Falseを返します。
使ってみると次のようになります。
# coding: shift-jis
from System.Text.RegularExpressions import *
word = "and that government of the people, by the people, for the people,"
pattern = "people"
print Regex.IsMatch(word, pattern) ←Trueになります。
print Regex.IsMatch(word, "Japanese") ←Falseになります。
raw_input()
出力画面:
True
False
Matchメゾット
Regex.Match(Str, Pattern)
patternで指定された正規表現を使用して、その正規表現と一致する対象がStr文字列内に見つかるか調べます。その結果をMatchクラスとして返します。
例えば、次のようなことができます。
# coding: shift-jis
from System.Text.RegularExpressions import *
word = "and that government of the people, by the people, for the people,"
pattern = "people"
m = Regex.Match(word, pattern)
print word[:m.Index] + "<" + m.Value +">" + word[m.Index+m.Length:]
raw_input()
出力画面:
and that government of the <people>, by the people, for the people,
ここで検索した結果が入っているMatchクラスについて、もう少し詳しくみていきましょう。Matchクラスのプロパティ
Match.Index見つかった文字列の最初の文字の位置を示します。
Match.Value
見つかった文字列を返します。
Match.Length
見つかった文字列の長さを示します。
Match.Success
検索した結果、検索が成功したか、失敗したかをbool値で返します。
Matchクラスのメゾット
Match.NextMatch()次にマッチする箇所を探してMatchクラスを返します。
Match.Result(String)
Matchクラスの結果を指定した置換文字列Stringで置換して返します。
先と同じことをMatch.Result()を使うと次のようになります。Resultメゾットの関数置換文字列Stringは正規表現と同じなのがわかると思います。
# coding: shift-jis
from System.Text.RegularExpressions import *
word = "and that government of the people, by the people, for the people, shall not perish from the earth. "
pattern = "people"
m = Regex.Match(word, pattern)
print m.Result("$`<$0>$'")
raw_input()
出力画面:
and that government of the <people>, by the people, for the people,
次はwhile文を使って対象箇所すべてを検索してみましょう。# coding: shift-jis
from System.Text.RegularExpressions import *
word = "and that government of the people, by the people, for the people,"
pattern = "people"
m = Regex.Match(word, pattern)
while m.Success : ←検索が失敗するまで繰り返す。
print m.Result("$`<$0>$'")
m = m.NextMatch()
raw_input()
出力画面:
and that government of the <people>, by the people, for the people,
and that government of the people, by the <people>, for the people,
and that government of the people, by the people, for the <people>,
Replaceメゾット
Regex.Replace(Str, Pattern, ReplaceText)Matchメゾットでも、一つ一つの検索結果によって対応を細かく決められるので置換することできますが、Replaceメゾットでは一変に置換してくれます。例を見てみましょう。
# coding: shift-jis
from System.Text.RegularExpressions import *
word = "and that government of the people, by the people, for the people,"
pattern = "people"
print Regex.Replace(word, pattern, "Japanese")
raw_input()
出力画面:
and that government of the Japanese, by the Japanese, for the Japanese,
ReplaceTextに置換の正規表現が使えたらすごいですよね。やってみてください、できちゃいます。# coding: shift-jis
from System.Text.RegularExpressions import *
word = "and that government of the people, by the people, for the people,"
pattern = "people"
print Regex.Replace(word, pattern, "<$0>") ←$0はMatch.Valueと同じ
raw_input()
出力画面:
and that government of the <people>, by the <people>, for
the <people>,
Regex.Replace(Str, Pattern, MatchEvaluator )
もう少し複雑なことをさせたいときは、MatchEvaluator デリゲートを使います。なんか難しい言い方をしていますが、簡単にいうとMatchを引数にもち、文字列を返す関数のことです。使い方はこんな感じです。
# coding: shift-jis
from System.Text.RegularExpressions import *
word = "and that government of the people, by the people, for the people,"
pattern = "people"
def replacetext(match): ←これが『MatchEvaluator デリゲート』です。
return match.Value.upper()
print Regex.Replace(word, pattern, replacetext) ←デリゲートは名前で指定。
raw_input()
出力画面:
and that government of the PEOPLE, by the PEOPLE, for the PEOPLE,
.NET FrameworkのMatchクラスを使って、Python文字列のメゾットを使っています。まさにコラボだと思います。追記:
見落とされているかも知れないので再度書きました。
正規表現の詳細は.NET Frameworkで使える正規表現で説明します。