【问题标题】:How to find specific character in string without effecting original var如何在不影响原始var的情况下查找字符串中的特定字符
【发布时间】:2020-05-13 07:57:51
【问题描述】:

我有“id#a1-beAklA23A”,我想只在“-”之后找到第一个“A”,并在没有太多代码(如绑定等)的情况下替换它

我试过了:

    dim item = "id#a1-beAklA23A"
    dim id = item.Split("-"c)

    Dim regex = New Regex("A", RegexOptions.IgnoreCase)
    id = regex.Replace(id, "#", 1)

    console.WriteLine(id)

它给我的错误是 Replace 不能与 String() 'array' 一起工作

而且我的代码不能正常工作,因为它只会在“-”之后输出内容并替换。我需要在“-”之前和“-”之后绑定 当我有很多东西时,它就不实用了

【问题讨论】:

    标签: .net regex vb.net


    【解决方案1】:

    错误是因为id 是一个数组 - 由拆分item 生成的字符串组成。

    您可以限制 Split 返回的部件数量。

    Dim item = "id#a1-beAklA23A"
    Dim id = item.Split({"-"c}, 2)
    
    Dim re = New Regex("A", RegexOptions.IgnoreCase)
    Dim item2 = id(0) & "-" & re.Replace(id(1), "#", 1)
    
    Console.WriteLine(item2)
    

    【讨论】:

      【解决方案2】:

      没有拆分和正则表达式的解决方案:

      Dim item = "id#a1-beAklA23A"
      
      If item Like "*-*[aA]" Then
          Dim index As Integer = item.IndexOf("A", item.IndexOf("-"c), StringComparison.InvariantCultureIgnoreCase)
          item = item.Remove(index, 1)
          item = item.Insert(index, "#")
          Console.WriteLine(item)
      End If
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-20
        • 2014-11-24
        • 1970-01-01
        • 1970-01-01
        • 2021-12-22
        • 2011-05-10
        相关资源
        最近更新 更多