代码之家  ›  专栏  ›  技术社区  ›  Chase Florell

构建一致URL(路由)所需的概念

  •  1
  • Chase Florell  · 技术社区  · 14 年前

    我的项目需要构建与StackOverflow上类似的一致的URL。我知道如何通过多个过滤器运行这个字符串来完成它,但是我想知道是否可以用一个方法来完成所有的工作。

    基本上,我想删除所有特殊字符,并用破折号替换它们,但是如果一行中有多个破折号,我需要它们是一个破折号。我怎样才能尽可能干净地实现这一点?

    示例:如果要使用以下字符串。

    我的活动

    我的 regex将创建以下字符串

    我的——1项活动

    注意有两个破折号(一个代表空格,一个代表“”符号)。我需要的是

    我的活动

    下面是我目前如何实现它

        ''# <System.Runtime.CompilerServices.Extension()>
        Public Function ToUrlFriendlyString(ByVal input As String) As String
            Dim reg As New Regex("[^A-Za-z0-9]")
            ''# I could run a loop filter here to match "--" and replace it with "-"
            ''# but that seems like more overhead than necessary.
            Return (reg.Replace(Trim(input), "-"))
        End Function
    

    然后我要做的就是调用扩展方法

        Dim UrlFriendlyString = MyTile.ToUrlFriendlyString
    

    事先谢谢。

    2 回复  |  直到 14 年前
        1
  •  2
  •   Chase Florell    14 年前

    +

    Regex Shared

        Private UrlRegex As Regex = New Regex("[^a-z0-9]+", RegexOptions.IgnoreCase)
    
        <System.Runtime.CompilerServices.Extension()>
        Public Function ToUrlFriendlyString(ByVal input As String) As String
            Return (UrlRegex.Replace(Trim(input), "-"))
        End Function
    
        2
  •  0
  •   Mike Geise    14 年前

    ''# <System.Runtime.CompilerServices.Extension()>    
    Public Function ToUrlFriendlyString(ByVal input As String) As String
        If [String].IsNullOrEmpty(s) = True Then
            Return [String].Empty
        End If    
    
        Dim builder As New StringBuilder()
        Dim slug = input.Trim().ToLowerInvariant()
    
        For Each c As Char in slug
            Select Case c
                Case ' '
                    builder.Append("-")
                Case '&'
                    builder.Append("and")
                Case Else
                    If (c >= '0' And c <= '9') OrElse (c >= 'a' And c <= 'z') And c != '-')
                        builder.Append(c)
                    End If
            End Select
        Next
    
        Return builder.ToString()
    End Function