Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.Net Remove Everything After Third Hyphen

Tags:

regex

vb.net

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.

like image 658
Alex Avatar asked Dec 15 '22 16:12

Alex


2 Answers

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);
like image 186
Steve Avatar answered Jan 07 '23 00:01

Steve


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).

like image 34
Neolisk Avatar answered Jan 07 '23 01:01

Neolisk