Reputation: 4948
Here is the string I am looking to modify: 170-0175-00B-BEARING PLATE MACHINING.asm:2
I want to keep "170-0175-00B". So I need to remove the third hyphen and whatever is after it.
Upvotes: 4
Views: 1304
Reputation: 26454
What about some LINQ?
Dim str As String = "170-0175-00B-BEARING PLATE MACHINING.asm:2"
MsgBox(String.Join("-"c, str.Split("-"c).Take(3)))
With this approach, you can take anything out after Nth hyphen, where N is easily controlled (a const).
Upvotes: 4
Reputation: 4948
Thanks so much for such fast replies.
Here's the path that I took:
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
Works great!
Upvotes: 2
Reputation: 40669
Something like this?
regex.Replace(sourcestring,"^((?:[^-]*-){2}[^-]*).*","$1",RegexOptions.Singleline))
You may not want the Singleline option though, depending how you use it.
Upvotes: 2
Reputation: 216323
A rapid solution
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);
of course, if you are searching for the last hyphen then is more simple to do
int index = test.LastIndexOf('-');
if(index > 0)
test = test.Substring(0, index);
Upvotes: 4