1

我正在尝试使用 VB.NET (3.5) 中的正则表达式从输入字符串中删除所有非 ascii 字符。我有一个函数应该通过正则表达式运行任何输入字符串:

Public Shared Function RemoveIllegalCharacters(ByVal inpTxt As String) As String

    'use a regular expression to replace any characters that are non-ascii
    inpTxt = Regex.Replace(inpTxt, "[^\u0000-\u007F]", String.Empty)

    Return inpTxt

End Function

这似乎在函数中正常工作。inpTxt = "123foobar" 在整个函数中都是 "123foobar"。但是,当我在其他地方访问它时:

Public someOtherFunction(ByVal inpTxt As String) As String

    inpTxt = RemoveIllegalCharacters(inpTxt)

    Return inpTxt

End Function

第一个字符消失:

inpTxt = "23foobar"

其他消息来源建议我写

inpTxt = Regex.Replace(inpTxt, @"[^\u0000-\u007F]", String.Empty)

但是该项目拒绝在没有 Regex.Replace 的第二个参数的字符串的情况下进行编译。

4

1 回答 1

2

这个函数没有意义:

Public Shared Sub RemoveIllegalCharacters(ByVal inpTxt As String)

    'use a regular expression to replace any characters that are non-ascii
    inpTxt = Regex.Replace(inpTxt, "[^\u0000-\u007F]", String.Empty)

End Sub

如果通过 ByVal 传递 inpTxt,则此函数不执行任何操作。它不会更改来自调用者的字符串,分配仅在 Sub 内部有效。您可以将您的 Sub 更改为 Function 并返回它:

Public Shared Function RemoveIllegalCharacters(ByVal inpTxt As String) As String

    'use a regular expression to replace any characters that are non-ascii
    Return Regex.Replace(inpTxt, "[^\u0000-\u007F]", String.Empty)

End Function

并像这样使用它:

Dim cleaned = RemoveIllegalCharacters(inpTxt)

这似乎有效:

Dim inpTxt = "1234FOOBARR" + Chr(&H80)
Console.WriteLine(inpTxt) 'Prints "1234FOOBARR?"
Dim cleaned = RemoveIllegalCharacters(inpTxt)
Console.WriteLine(cleaned) 'Prints "1234FOOBARR"
于 2013-06-14T17:27:37.063 回答