2

在字符串上,我必须在字符串中添加一些空格以进行填充,如下所示:

Dim whiteSpace As Char = CChar(HttpUtility.HtmlDecode(" "))
tempDisplay.Append(whiteSpace, paddingNeeded)

会给我类似的东西:

A99      - More Text

现在稍后,我需要删除该空间。我试过了:

Dim indexOfDash As Integer = curLinkBtn.Text.IndexOf("-")
Dim testForWhiteSpace As Integer = indexOfDash - 2
Dim whiteSpace As String = " "c 'This and nbsp are both in just to see if they would work
Dim nbsp As Char = CChar(HttpUtility.HtmlEncode(" "))

'See if there has been whitespace injected at all
 If Char.IsWhiteSpace(curLinkBtn.Text(testForWhiteSpace)) Then
         Dim regReplave As String = Regex.Replace(curLinkBtn.Text, whiteSpace, "!", RegexOptions.IgnoreCase) 
         'That produces A99      -!More!Text 
         Dim regReplaveNbsp As String = Regex.Replace(curLinkBtn.Text, nbsp, "*", RegexOptions.IgnoreCase)
         'On this I don't even get the '*'
         curLinkBtn.Text = regReplave
         Dim testChar As Char = curLinkBtn.Text(testForWhiteSpace)
 End If

感谢您的任何指点

4

1 回答 1

1

尝试使用\s(空格的简写)而不是" "c:

Dim input = "A99      - More Text"
Dim pattern = "\s|( )"
Dim result = System.Text.RegularExpressions.Regex.Replace(input, pattern, "!")
' produces "A99!!!!!!-!More!Text"

这也适用于制表符:

Dim input = "A99    - More Text" ' uses a tab character
' produces "A99!-!More!Text"

从技术上讲,如果您的字符串被解码,那么 在那个正则表达式模式中并不重要,但我把它扔在那里是为了很好的衡量标准。

或者,如果您只想擦除连字符周围的空白,您可以更改正则表达式以搜索它并在 Regex.Replace 中用普通连字符替换它:

Dim input = "A99          - More Text"
Dim pattern = "(\s|( ))*-(\s|( ))*"
Dim result = System.Text.RegularExpressions.Regex.Replace(input, pattern, "-")
' produces "A99-More Text"
于 2013-11-12T20:29:29.863 回答