在字符串中的某个字符后删除空格的最佳方法是什么?

时间:2009-04-17 14:24:43

标签: vb.net string

我正在尝试构建一个列表,该列表将用作select语句的in子句。要求是让用户输入以逗号分隔的描述列表。每个描述都可以包含空格,因此我不能在用逗号分割之前删除空格,以在每个描述周围添加单引号。我希望在单引号后删除所有空格,因为没有描述将以空格开头。在VB.NET中执行此操作的最佳方法是什么?正则表达式还是字符串函数?这是我到目前为止所拥有的。:

Partial Class Test
    Inherits System.Web.UI.Page

    Protected Sub cmdGetParts_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdGetParts.Click
        Dim sDescriptionList As String = ""
        BuildList(sDescriptionList)
        RemoveSpacesFromList(sDescriptionList)
        FillGrid(sDescriptionList)
    End Sub

    'Build descriptions List based on txtDescriptionList.Text
    Private Sub BuildList(ByRef sDescriptionList As String)
        Dim sDescriptionArray As String()
        sDescriptionArray = txtDescriptionList.Text.Trim.Split(","c)
        Dim iStringCount As Integer = 0
        For Each description In sDescriptionArray
            If iStringCount > 0 Then
                sDescriptionList = sDescriptionList & ","
            End If
            sDescriptionList = sDescriptionList & "'" & description & "'"
            iStringCount = iStringCount + 1
        Next
    End Sub

    **'This procedure removes unwanted spaces from  description list
    Private Sub RemoveSpacesFromList(ByRef sList As String)
        sList = sList.Replace("' ", "'")
    End Sub**

    'This procedure fills the grid with data for descriptions passed in
    Private Sub FillGrid(ByVal sDescriptionList As String)
        Dim bo As New boPart
        Dim dtParts As Data.DataTable
        dtParts = bo.GetPartByDescriptionList(sDescriptionList)
        GridView1.DataSource = dtParts
        GridView1.DataBind()
    End Sub
End Class 

已编辑:在查看此代码后,我想我可以放置 description.Trim在BuildList过程的For Each循环中。

2 个答案:

答案 0 :(得分:2)

只要您不能嵌入单引号,以下内容就应该诀窍

Dim replaced = Regex.Replace(input, "'\s+", "'")

正则表达式字符串'\s+将匹配任何单引号,后跟一个或多个空格字符。此匹配的所有实例将替换为单引号。

答案 1 :(得分:1)

使用正则表达式将逗号与任何周围的空格匹配,并用apostropes和逗号替换。第一个项目的起始副本和最后一个项目的结尾撇号,之后只需添加。

不再需要RemoveSpacesFromList方法,因为BuildList方法可以完成所有操作。

Protected Sub cmdGetParts_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdGetParts.Click
    Dim descriptions As String = txtDescriptionList.Text
    descriptions = BuildList(descriptions)
    FillGrid(descriptions)
End Sub

''//Build descriptions List based on a comma separated string
Private Function BuildList(ByVal descriptions As String) As String
   Return "'" + Regex.Replace(descriptions, "\s*,\s*", "','", RegexOptions.Compiled) + "'"
End Function

注意:
如果您使用此字符串来构建SQL查询,那么您的应用程序可以进行SQL注入攻击。使用参数化查询是首选方法,但在您的情况下可能不方便。在用于查询之前,必须至少对用户输入进行清理。

编辑:
如果适配器在字符串文字中使用撇号作为转义字符,则可以正确转义字符串,如下所示:

Private Function BuildList(ByVal descriptions As String) As String
   Return "'" + Regex.Replace(descriptions.Replace("'","''"), "\s*,\s*", "','", RegexOptions.Compiled) + "'"
End Function