ASP中轻松实现变量名-值变换
来源:互联网 发布:网页制作三剑客软件 编辑:程序博客网 时间:2024/05/29 04:21
用过PHP的朋友都知道,PHP中变量的使用灵活方便,特别是能在字符串中方便实现变量名-值变换,使得整个PHP代码更显简洁优美。比如一条更新数据库的SQL语句只需写成:"update users set password='$password', group=$group, name='$username' where account='$account'",其中的$password、$group、$username、$account便会被实际的变量值替换,而在ASP中要实现相同的功能必须写成:"update useres set password='" & password & "',group=" & group & ",name='" & username & "' where account='" & account & "'",显得冗长难看。如果这是一条insert语言而且插入的字段内容很多的话,那么查看字段与values的对应关系将会是一个痛苦的过程。
现在让我们看看如何在ASP实现类似的变量名-值变换。
思路
首先,必须有一个方法把需要用实际值替换的变量名与普通的文本区分出来;然后,把所有找到的变量名用它所代表的实际值替换掉。
对于第一点可以通过正则表达式查找得到,这里我们不采用PHP的变量表示方式,而采用大托号{}作为变量名的边界符,字符串表示变为password='{password}',group={group}。
第二点是变量名-值变换的关键,通过变量名得到变量值。查看ASP资料没有找到直接实现的方法,但有一个函数Execute引起我们的注意,从资料说明中可知Execute可以执行传入的有效的字符串作为代码执行同,这样只要编写一个小函数就可以实现我们的要示。核心代码为:
function GetVar(var_name)
Execute("function get_value(): get_value=" & var_name & ": end function")
getvar=get_value()
end function
实现
完整代码:
function GetVar(var_name)
Execute("function get_value(): get_value=" & var_name & ": end function")
getvar=get_value()
end function
function Txt2Value(str, level)
dim regEx, Matches, Result
Set regEx = new RegExp
select case level
case 0 regEx.Pattern = "\{(\w+)\}" '变量名有效
case 1 regEx.Pattern = "\{([\w+\-\*/\\<>=]+)\}" '变量名及运算符有效
'case 2 regEx.Pattern = "\{([\w\s]+)\}" '除换行符外的所有字符有效
case else exit function
end select
'regEx.Pattern = "\{(\w+)\}"
regEx.IgnoreCase = true
regEx.Global = true
Set Matches = regEx.Execute(str)
Result = str
'response.write Matches.Count
For Each Match In Matches
Result = Replace(Result, Match.Value, GetVar(Match.SubMatches(0)))
Next
set Matches = nothing
set regEx = nothing
Txt2Value = Result
end function
function Var2Value(var_name)
Var2Value = Txt2Value(var_name, 0)
end Function
调用方法:
Var2Value("update users set password='{password}', group={group}, name='{username}' where account='{account}'"
Var2Value调用了Txt2Value,Txt2Value找出所有变量名交调用GetVar得到变量值并进行替换。实际上直接调用Txt2Value(str,1)还允许对字符串值进行四则运算。
- ASP中轻松实现变量名-值变换
- ASP中轻松实现变量名-值变换
- 在ASP.NET中轻松实现加密
- asp.net 同一个页面中如何保持变量的值在多个事件中变换???
- ASP.NET 2.0中轻松实现网站换肤
- ASP.NET 2.0中轻松实现网站换肤
- ASP.NET 2.0中轻松实现网站换肤
- 在ASP中轻松实现记录集分页显示
- ASP.NET 2.0中轻松实现网站换肤
- ASP.NET 2.0中轻松实现网站换肤
- ASP.NET 2.0中轻松实现网站换肤
- 在ASP中轻松实现记录集分页显示
- ASP.NET 2.0中轻松实现网站换肤
- ASP.NET 2.0中轻松实现网站换肤
- ASP.NET 2.0中轻松实现网站换肤
- ASP.NET 2.0中轻松实现网站换肤
- ASP.NET2.0中轻松实现网站换肤
- ASP.NET 2.0中轻松实现网站换肤
- C++ stw与setfill
- 计算机网络之二
- Java类的编译和运行
- 第一次当开发负责人的流水账
- Lua 字符串库函数总结
- ASP中轻松实现变量名-值变换
- 机器学习,推荐系统
- 在ASP+ 中我们如何使用 Class 而不是组件
- Java 强引用、弱引用、软引用和虚引用和JVM
- 在Web界面下如何生成像资源管理器一样的树形目录
- android开发经验
- Linux下软件的命令行安装
- 关于Wampserver安装完成后无法启动MySQL的问题
- maven 从svn导入项目遇到的问题 No marketplace entries found to handle yuicompressor maven plugin:1.3.0:compile