// param1 type : String, ... // return type : xpeg::Executor or Null String::match: method(pattern);
XtalのString::matchは、patternにmatchする文字列があった場合、その文字列をcaptureした瞬間のExecutorを、matchする文字列がなかった場合はnullを返します。
返ってきたExecutorを使うことで、matchした文字列のprefixやsuffixを得ることが出来たり、matchした後の処理を続けることが出来ます。
“foo”にマッチする文字列が存在する限り処理を続ける
-
str : "foobarfoobarhogehoge"; e : str.match("foo"); if (e){ e.captures{|k, value| value.p; } e.prefix.p; e.suffix.p; while (e.match("foo")){ e.captures{|k, value| value.p; } e.prefix.p; e.suffix.p; } }
foo barfoobarhogehoge foo bar barhogehoge
String_gsubの実装
-
fun String_gsub(str, pattern, fn){ mm : MemoryStream(); exec : str.match(pattern); if (exec){ prefix : exec.prefix; mm.put_s(prefix); mm.put_s(fn(exec)); while (exec.match(pattern)){ prefix : exec.prefix; mm.put_s(prefix); mm.put_s(fn(exec)); } mm.put_s(exec.suffix); return mm.to_s; } else { return str; } } String_gsub("foobar piyo hoge foo", "foo", "bar").p;
barbar piyo hoge bar