2006/06/21(水)正規表現モジュール
サンプルのcomtest8.hspを適当にいじくり回してみた。
HSP3でVBScript.RegExpの正規表現を使うwrapperモジュ。
match のサブ式の部分が面倒くさいので今のところノータッチ。
こんなんあるなら最初から reptext.hsp なんて作らんのに(´ω`)
#module vbsregexp
#define ctype IsKanji(%1) ((((%1)^$20)-$a1&$ff)<=$3b)
#defcfunc uniptrtombptr var sample, int letters, int startByte, local ptr
ptr = startByte
repeat letters
if IsKanji(peek(sample,ptr)) : ptr+2 : else : ptr++
loop
return ptr-startByte
#deffunc regexp_replace var buf, str from, str to, int opt, local oRegExp, local strResult
newcom oRegExp,"VBScript.RegExp"
comres strResult
oRegExp("Pattern")=from
oRegExp("Global")=opt&1;// 常に1でもいいか
oRegExp("IgnoreCase")=opt&2
oRegExp("Multiline")=opt&4
oRegExp->"Replace" buf,to
buf = strResult
delcom oRegExp
return
#deffunc regexp_match var buf, str pattern, int opt, local oRegExp, local oMatches, local oMatch
newcom oRegExp,"VBScript.RegExp"
comres oMatches
oRegExp("Pattern")=pattern
oRegExp("Global")=opt&1
oRegExp("IgnoreCase")=opt&2
oRegExp("Multiline")=opt&4
oRegExp->"Execute" buf
MatchCount = oMatches("Count")
if MatchCount {
dim matchPos,MatchCount
dim matchLen,MatchCount
repeat MatchCount
oMatch = oMatches("Item",cnt)
matchPos.cnt = uniptrtombptr(buf,oMatch("FirstIndex"),0)
matchLen.cnt = uniptrtombptr(buf,oMatch("Length"),matchPos.cnt)
delcom oMatch
loop
}
delcom oMatches
delcom oRegExp
return MatchCount ;// hit数
#defcfunc regexp_getPos int c
if c<0 : return -1
if c>=MatchCount : return -1
return matchPos.c
#defcfunc regexp_getLen int c
if c<0 : return 0
if c>=MatchCount : return 0
return matchLen.c
#global
mes "---- match sample"
buf = "今日は雨ですが、明日は晴れです。"
from = "日は.*?です"
mes "対象文字列: " + buf
mes "パターン : " + from
regexp_match buf,from,1|2;// オプションは 1:g 2:i 4:m の論理和
MatchCount = stat
mes "ヒット数 = "+MatchCount
repeat MatchCount
mes " マッチ文字列 = " + strmid(buf, regexp_getPos.cnt, regexp_getLen.cnt)
mes " 位置("+cnt+") = " + regexp_getPos.cnt
mes " 長さ("+cnt+") = " + regexp_getLen.cnt
loop
mes "\\n---- replace sample"
buf = "今日は晴れですね。"
from = "今日は(.*?)です"
to = "明日も$1だよ" ;// '$' は $$ で表現
mes "対象文字列: " + buf
mes "パターン : " + from
mes "置換後 : " + to
regexp_Replace buf,from,to,1|2
mes buf