我可以在RegEx模式中使用变量吗?

时间:2014-02-16 15:59:19

标签: regex vb.net variables

("/gallery/static/newest/\d*/desc/\d*/nosets/19/")

工程....

("/gallery/static/newest/\d*/desc/\d*/nosets/" & strAge & "/")

不起作用....

如何让我的RegEx模式与变量一起使用?或者不是吗?

1 个答案:

答案 0 :(得分:0)

正如Karl Kieninger所说,似乎有可能在strAge中有额外的角色。你可以删除它们。根据sln的想法,一旦你有一个干净的字符串,你可以将,改为|

Imports System.Text.RegularExpressions

Module Module1

    Sub Main()
        Dim textToCheck As String = "/gallery/static/newest/123/desc/456/nosets/20/"

        Dim strAge As String = "18,19,20,21"
        ' remove any unwanted chars and change the ","s to "|"s.
        strAge = Regex.Replace(strAge, "[^0-9,]", "").Replace(","c, "|"c)
        Dim pattern As String = "/gallery/static/newest/\d*/desc/\d*/nosets/(?:" & strAge & ")/"
        Console.WriteLine(pattern)
        Console.WriteLine(textToCheck & " " & Regex.IsMatch(textToCheck, pattern).ToString)

        Console.ReadLine()

    End Sub

End Module

输出:

/gallery/static/newest/\d*/desc/\d*/nosets/(?:18|19|20|21)/
/gallery/static/newest/123/desc/456/nosets/20/ True

另外,您是真的意味着\d*或更多次出现)还是\d+一次或更多次出现)更好?