【问题标题】:VB.Net Remove Everything After Third HyphenVB.Net 删除第三个连字符后的所有内容
【发布时间】:2012-11-28 07:40:16
【问题描述】:

这是我要修改的字符串: 170-0175-00B-轴承板加工.asm:2

我想保留“170-0175-00B”。所以我需要删除第三个连字符以及它后面的任何内容。

【问题讨论】:

  • 第三个连字符也总是最后一个连字符吗?

标签: regex vb.net hyphen


【解决方案1】:

一些 LINQ 怎么样?

Dim str As String = "170-0175-00B-BEARING PLATE MACHINING.asm:2"
MsgBox(String.Join("-"c, str.Split("-"c).Take(3)))

使用这种方法,您可以在第 N 个连字符之后取出任何内容,其中 N 很容易控制(一个 const)。

【讨论】:

    【解决方案2】:

    非常感谢这么快的回复。

    这是我选择的路径:

    FormatDessinName("170-0175-00B-BEARING PLATE MACHINING.asm:2")
    
    
    Private Function FormatDessinName(DessinName As String)
        Dim match As Match = Regex.Match(DessinName, "[0-9]{3}-[0-9]{4}-[0-9]{2}[A-Za-z]([0-9]+)?") 'Matches 000-0000-00A(optional numbers after the last letter)
        Dim formattedName As String = ""
    
        If match.Success Then 'Returns true or false
            formattedName = match.Value 'Returns the actual matched value
        End If
    
        Return formattedName
    End Function
    

    效果很好!

    【讨论】:

      【解决方案3】:

      这样的?

      regex.Replace(sourcestring,"^((?:[^-]*-){2}[^-]*).*","$1",RegexOptions.Singleline))
      

      你可能不想要 Singleline 选项,这取决于你如何使用它。

      【讨论】:

        【解决方案4】:

        快速解决方案

        string test = "170-0175-00B-BEARING PLATE MACHINING.asm:2";
        int num = 2;
        int index = test.IndexOf('-');
        while(index > 0 && num > 0)
        {
            index = test.IndexOf('-', index+1);
            num--;
        }
        if(index > 0)
            test = test.Substring(0, index);
        

        当然,如果您要搜索最后一个连字符,则更简单

        int index = test.LastIndexOf('-');
        if(index > 0)
            test = test.Substring(0, index);
        

        【讨论】:

        • 谢谢史蒂夫,我没有注意到你们回复得这么快,所以我正在研究自己的解决方案。终于,我明白了(明天我能回复我的帖子时,我会发布它)。
        • 难以预测,但通常很快就会得到答案
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-03
        • 2021-11-20
        • 2012-10-01
        • 2022-08-19
        • 1970-01-01
        • 2012-10-19
        • 1970-01-01
        相关资源
        最近更新 更多