Asp判断中文汉字

第一种用 ASCII 码判断,缺点:把全角逗号“,”当汉字处理

在 ASCII码表中,英文的范围是0-127,而汉字则是大于127,具体代码如下:

text="是不是汉字,ABC。"
for i=1 to len(text)
response.write Mid(text,i,1)&":"&abs(asc(Mid(text,i,1)))
if abs(asc(Mid(text,i,1)))>127then 
Response.Write("是汉字")
else
Response.Write("不是汉字")
end if
response.write "<br>"
next
输出看,的确将最后的全角句号识别成了汉字。

第二种用汉字的 UNICODE 编码范围判断,

text="是不是汉字,ABC。"
for i=1 to len(text)
response.write mid(text,i,1)&":"& hex(AscW(Mid(text,i,1)))
if hex(AscW(Mid(text,i,1)))>="4e00" and hex(AscW(Mid(text,i,1)))<= "9fbb" then
Response.Write("是汉字")
else
Response.Write("不是汉字")
end if
response.write "<br>"
next

注意代码中的&号不要和hex紧挨着,要分开一个空格,否则程序会出错。

第三种用正则表达式判断

text="是不是汉字,ABC。"
for i=1 to len(text)
response.write Mid(text,i,1)&":"&abs(asc(Mid(text,i,1)))
set regexpobj=new regexp 
regexpobj.pattern="^[\u4e00-\u9fa5]+$" 
regcheck=regexpobj.test(Mid(text,i,1)) 
set regexpobj=nothing 
if regcheck then 
response.write "是汉字" 
else 
response.write "不是汉字" 
end if 
response.write "<br>"
next 

附两个小函数

'中文转unicode
function tounicode(str)
tounicode=""
dim i
for i=1 to len(str)
'asc函数:返回字符串的第一个字母对应的ANSI字符代码
'AscW函数:返回每一个GB编码文字的Unicode字符代码
'hex函数:返回表示十六进制数字值的字符串
tounicode=tounicode & "\u" & LCase(Right("0000" & Cstr(hex(AscW(mid(str,i,1)))),4))
next
end function

'unicode转中文
function unicodeto(str) 
str=replace(str,"\u","")
unicodeto=""
dim i
for i=1 to len(str) step 4
'cint函数:将Variant类型强制转换成int类型
'chr函数:返回数值对应的ANSI编码字符
'ChrW函数:返回数值对应的Unicode编码字符
unicodeto=unicodeto & ChrW(cint("&H" & mid(str,i,4)))
next
end function