【问题标题】:Trim a string - remove space and parentheses in VB.NET修剪字符串 - 删除 VB.NET 中的空格和括号
【发布时间】:2015-10-20 15:15:32
【问题描述】:

有人可以帮我解决这个问题吗?

在 vb.net (VS2013) 中: 字符串格式为:char12345 (6789).jpg

将字符串修剪为:char12345.jpg

基本上,我需要修剪中间部分:空格和括号中的所有内容(包括括号)。

VB 的修剪功能会起作用吗?或者我需要使用正则表达式...

提前非常感谢!

【问题讨论】:

  • Would someone help me with this please 请您发布您尝试过的内容吗?见How to Ask
  • “VB的trim功能会起作用吗?”没有。“或者我需要使用RegEx”不一定。但是你在什么时候被卡住了?您是否对字符串操作进行过任何研究,无论是否使用正则表达式?
  • 括号总是在末尾吗?

标签: vb.net string trim


【解决方案1】:

您不需要正则表达式,您也可以使用纯字符串方法删除括号:

Dim path = "char12345 (6789).jpg"
Dim ext = IO.Path.GetExtension(path)
Dim fn = IO.Path.GetFileNameWithoutExtension(path)
Dim index = fn.IndexOf("(")
If index >= 0 Then fn = fn.Remove(index).Trim()
path = String.Format("{0}{1}", fn, ext)

假定它们总是直接在扩展之前,或者它们后面的部分也可以被删除。否则它会变得有点复杂:

Dim index = fn.IndexOf("(")
If index >= 0 Then
    Dim endindex = fn.LastIndexOf(")", index)
    If endindex >= 0 Then
        fn = fn.Remove(index).Trim() & fn.Substring(endindex + 1)
    Else
        fn = fn.Remove(index).Trim()
    End If
End If

【讨论】:

  • 所有优秀的cmets。确实需要审查字符串操作。 Schmelter 先生的解决方案非常有用。 InbetweenWeekends 的解决方案适用于我所说的特定格式,但我意识到有些字符串没有括号。我的情况需要检查 Index >= 0 。谢谢!
【解决方案2】:

根据您的意见,您可以通过 Split 完成此操作

Dim str as String = "char12345 (6789).jpg"
Console.Write(str.Split(" ")(0) & "." & str.Split(".")(1))

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多