最終更新: yamanobori_old 2011年12月11日(日) 17:25:44履歴
Ruby | Perl | .NET |
myregexp = /pattern/ myregexp = Regexp.new(userinput) | $myregexp = qr/pattern/; $myregexp = qr/$userinput/; | Regexp reg = new Regexp("pattern"); try { Regexp reg = new Regexp(userinput); } catch (ArgumentExeption){} |
Ruby | Perl | .NET | |
フリーフォーマット | /rまたはRegexp::EXTENED | /x | RegexOptions.IgnorePatternWhitespace |
大文字と小文字を区別しないマッチ | /iまたはRegexp::IGNORECASE | /i | RegexOptions.IgnoreCase |
ドットで改行にマッチ | /mまたはRegexp::MULTILINE | /s | RegexOptions.SingleLine |
^と$で改行にマッチ | 常に改行にマッチ | /m | RegexOptions.MultiLine |
Ruby | Perl | .NET |
ファイルをオープンするときに,"r:utf-8"等,エンコーディングを指定する. 標準出力への書き込みはSTDOUT.set_encoding("CP932")等とする. | use utf8; use Encode; ファイルをUTF-8で書く.ファイルをオープンするときに,open my $fh,"<:encoding(cp932)",$file,のようにして,ファイルのエンコーディングを指定する.標準出力への書き込みは binmode STDOUT,":encoding(cp932);"のようにする. | StreamReader("test.txt",Encoding.GetEncoding("shift_jis")); |
Ruby | Perl | .NET |
$& | $& | Regex.Match().Value |
- 後方参照(名前付きキャプチャ)
Ruby | Perl | .NET |
$~[name] | $+{name} | Regex.Match().Groups["name"].Value |
Ruby | Perl | .NET |
scan(/regex/) {|match|do something} gsub(/regex/) {|match|do something} | foreach (/regexp/g) {do something} | foreach (Match m in Regex.Matches) {do something} |
Ruby |
scan(/regex/) {|match|match.scan(/Reregex/) 正規表現はネストなどの非線形コンテクストを管理できないので,手続き型コードにまかせるのが賢明. |
Ruby | Perl | .NET |
result = subject.gsub(/before/,'after') | subject =~ s/before/after/; 別変数に格納 ($result = $subject) =~ s/before/after/; | Regex.Replace(subject,"befor","after" |
Ruby | Perl | .NET |
gsub(/\d{4}/) {|match| match = (match.to_i * 2).to_s | $s =~ s/\d{4}/$& * 2/eg; | (詳細略)MatchEvaluatorを使う |
Ruby | Perl | .NET |
s = "before <b>first before</b> before <b>before before</b>" s.gsub!(/<b>.*?<\/b>/m) {|match|match.gsub!(/before/,'after')} | my $s = "before <b>first before</b> before <b>before before</b>"; $s =~ s!<b>.*?</b>!(my $match = $&) =~ s/before/after/g;$match!eg; | (詳細略)MatchEvaluatorを使う |
Ruby | Perl | .NET |
result = subject.gsub(/(\w+) = (\w+)/,'\2=\1') | $subject =~ s/(\w+) = (\w+)/$2=$1/g | string resultString = Regexp.Replace(subjectString,@"(\w+)=(\w+)","$2=$1") |
Ruby | Perl | .NET |
s = %!"text" <span class="middle">"text"</span> "test"! ->“text” <span class="middle">“text”</span> “test” result = "" while s =~ /<[^<>]*>/ match = $& after = $' before = $`.gsub(/"([^"]*)"/,'“\1”') result += before + match s = after end result += after.gsub(/"([^"]*)"/,'“\1”') |
Ruby | Perl | .NET |
s = "I like <b>bold</b> and <i> italic </i> fonts" s.split(/<[^<>]*?>/) | my $s = "I like <b>bold</b> and <i> italic </i> fonts"; say split(/<[^<>]*?>/,$s); | Regex.Split |
Ruby | Perl | .NET |
s = "I like <b>bold</b> and <i> italic </i> fonts" s.split(/(<[^<>]*?>)/) | my $s = "I like <b>bold</b> and <i> italic </i> fonts"; say split(/(<[^<>]*?)>/,$s); | Regex.Split |
コメントをかく