【发布时间】:2012-11-28 07:40:16
【问题描述】:
这是我要修改的字符串: 170-0175-00B-轴承板加工.asm:2
我想保留“170-0175-00B”。所以我需要删除第三个连字符以及它后面的任何内容。
【问题讨论】:
-
第三个连字符也总是最后一个连字符吗?
这是我要修改的字符串: 170-0175-00B-轴承板加工.asm:2
我想保留“170-0175-00B”。所以我需要删除第三个连字符以及它后面的任何内容。
【问题讨论】:
一些 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)。
【讨论】:
非常感谢这么快的回复。
这是我选择的路径:
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
效果很好!
【讨论】:
这样的?
regex.Replace(sourcestring,"^((?:[^-]*-){2}[^-]*).*","$1",RegexOptions.Singleline))
你可能不想要 Singleline 选项,这取决于你如何使用它。
【讨论】:
快速解决方案
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);
【讨论】: