這是我期待修改字符串: 170-0175-00B荷瘤板MACHINING.asm:2VB.Net刪除一切後三連字符
我想保持「170-0175 -00B「。所以我需要刪除第三個連字符以及後面的任何連字符。
這是我期待修改字符串: 170-0175-00B荷瘤板MACHINING.asm:2VB.Net刪除一切後三連字符
我想保持「170-0175 -00B「。所以我需要刪除第三個連字符以及後面的任何連字符。
,迅速解決
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);
像這樣的事情?
regex.Replace(sourcestring,"^((?:[^-]*-){2}[^-]*).*","$1",RegexOptions.Singleline))
雖然您可能不希望Singleline選項,具體取決於您如何使用它。
非常感謝這麼快的回覆。
下面是我採取的方法:
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
的偉大工程!
一些LINQ呢?
Dim str As String = "170-0175-00B-BEARING PLATE MACHINING.asm:2"
MsgBox(String.Join("-"c, str.Split("-"c).Take(3)))
通過這種方法,您可以在N連字符之後取出任何內容,其中N易於控制(常量)。
第三個連字符總是最後的連字符? –