使用经典的asp进行正则表达式

时间:2011-07-13 08:09:52

标签: regex asp-classic

我们有一些经典的asp网站,我正在研究它们,我想知道如何编写正则表达式检查,并提取匹配的表达式:

我所拥有的表达式是脚本的名称 所以我们这样说吧

Response.Write Request.ServerVariables("SCRIPT_NAME")

打印出来:

review_blabla.asp
review_foo.asp
review_bar.asp

如何从那里获得blablafoobar

感谢。

4 个答案:

答案 0 :(得分:18)

虽然Yots的答案几乎肯定是正确的,但你可以用更少的代码和更清晰的方式达到你想要的结果:

'A handy function i keep lying around for RegEx matches'
Function RegExResults(strTarget, strPattern)

    Set regEx = New RegExp
    regEx.Pattern = strPattern
    regEx.Global = true
    Set RegExResults = regEx.Execute(strTarget)
    Set regEx = Nothing

End Function

'Pass the original string and pattern into the function and get a collection object back'
Set arrResults = RegExResults(Request.ServerVariables("SCRIPT_NAME"), "review_(.*?)\.asp")

'In your pattern the answer is the first group, so all you need is'
For each result in arrResults
    Response.Write(result.Submatches(0))
Next

Set arrResults = Nothing

此外,我还没有找到更好的RegEx playground than Regexr,在深入研究代码之前试用你的正则表达式模式非常棒。

答案 1 :(得分:4)

您必须使用匹配对象中的子匹配集合才能从review_(.*?)\.asp模式中获取数据

Function getScriptNamePart(scriptname)
    dim RegEx : Set RegEx = New RegExp
    dim result : result = ""
    With RegEx
        .Pattern = "review_(.*?)\.asp"
        .IgnoreCase = True
        .Global = True
    End With

    Dim Match, Submatch
    dim Matches : Set Matches = RegEx.Execute(scriptname)    
    dim SubMatches
    For Each Match in Matches
        For Each Submatch in Match.SubMatches
                result = Submatch
        Exit For
        Next
    Exit For
    Next

    Set Matches = Nothing
    Set SubMatches = Nothing
    Set Match = Nothing
    Set RegEx = Nothing

    getScriptNamePart = result
End Function

答案 2 :(得分:0)

你可以做到

review_(.*?)\.asp

here on Regexr

然后,您将在捕获组1中找到结果。

答案 3 :(得分:0)

您可以使用RegExp对象执行此操作。 你的代码会是这样的:

Set RegularExpressionObject = New RegExp
RegularExpressionObject.Pattern = "review_(.*)\.asp"
matches = RegularExpressionObject.Execute("review_blabla.asp")

抱歉,我现在无法测试下面的代码。 查看MSDN http://msdn.microsoft.com/en-us/library/ms974570.aspx

的使用情况