65.9K
CodeProject 正在变化。 阅读更多。
Home

简化在脚本中使用正则表达式

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.86/5 (7投票s)

2001年7月23日

CPOL

1分钟阅读

viewsIcon

130455

downloadIcon

775

使正则表达式工作更容易的小型库。

引言

了解 正则表达式 的能力和语法,我希望在我的 VBScript 代码中拥有类似的语法。VBScript 使用 RegExp 对象,所以我将对 RegExp 对象的调用封装在三个函数中。

函数

rxTest

function rxTest( text, pattern, flags )

使用此函数测试字符串中的模式。其行为类似于 Perl 中的 =~ s// 运算符。

参数是

  • 文本
    执行正则表达式的文本字符串。
  • pattern
    要搜索的正则表达式字符串。
  • flags
    i:不区分大小写,g:全局,m:多行

如果找到则返回 true,否则返回 false。

rxReplace

function rxReplace( text, pattern, replace_text, flags )

使用此函数将字符串中的模式替换为另一个字符串。其行为类似于 Perl 中的 =~ m// 运算符。

参数是

  • 文本
    执行正则表达式的文本字符串。
  • pattern
    要搜索的正则表达式字符串。
  • replace_text
    替换文本字符串。
  • flags
    i:不区分大小写,g:全局,m:多行

返回修改后的字符串。此函数不会修改输入字符串。

rxExec

function rxExec( text, pattern, flags )

使用此函数测试字符串中的模式并返回匹配的元素。其行为类似于 Perl 中的 =~ s// 运算符。

参数是

  • 文本
    执行正则表达式的文本字符串。
  • pattern
    要搜索的正则表达式字符串。
  • flags
    i:不区分大小写,g:全局,m:多行

如果找到匹配项,则返回 Matches 集合,否则返回 nothing

示例

  • 检查给定的 URL 是否以特定的协议开头
    dim is_absolute
    is_absolute = rxTest( url, "^(https|http|ftp|mailto|javascript|jscript)://", "gis" )
  • 从字符串中删除特定的 HTML 标签(非常简单的版本!)
    dim blank
    blank = rxReplace( html, "<"&tag_name&"\b[^>]*>", "", "gi")
  • 将特定语法的所有出现替换为从数据库中查找的值
    do
      set matches = rxExec(html, "oid://([0-9]+)", "g")
    
      if not IsNothing(matches) then
        if matches.Count>0 then
          set match = matches(0)
    
          dim replacement
          if match.SubMatches.Count>0 then
            replacement = GetNameFromDatabaseByID(match.SubMatches(0))
          else
            replacement = ""
          end if
    
          html = Replace(html, match.Value, replacement)
        else
          exit do
        end if
      else
        exit do
      end if
    loop

最后一个示例使用了函数 IsNothing,该函数定义如下

function IsNothing( byref obj )
	IsNothing = CBool(LCase(TypeName(obj))="nothing")
end function
© . All rights reserved.