Reputation: 1568
I have these string:
Database_123456.bak
I need to take only the number:
123456
I do this:
Dim number As String = Replace("Database_123456.bak", "Database", "")
This return me:
123456.bak
And I have to add another variable to replace again the last part:
Dim FinalNumber as string = Replace(number, ".bak", "")
Is there any way to replace the two parts in the same line, to abbreviate?
thanks
Upvotes: 1
Views: 91
Reputation: 267
If I understood correctly this will work out for you
string text = "Database_123456.bak";
string number = text.Split('_')[1].Split('.')[0];
Upvotes: 1
Reputation: 1
string str = "Database_123456.bak";
string exteractNumber = string.Empty;
foreach (char c in str.ToCharArray())
{
int result;
if (int.TryParse(c.ToString(), out result))
{
exteractNumber = exteractNumber + c;
}
}
Upvotes: 0
Reputation: 172398
You can try using Regex:
Dim x As String = "Database_123456.bak"
Dim res = Integer.Parse(Regex.Replace(x, "[^\d]", ""))
or simply
Dim res = Regex.Matches("Database_123456.bak", "\d+")
Also you have to import
Imports System.Text.RegularExpressions
Upvotes: 2
Reputation: 27322
You can chain replacements together using [String].Replace
, so you can do it all in one line:
Dim finalNumber = "Database_123456.bak".Replace("Database_", "").Replace(".bak", "")
note: you missed out an underscore char in your first replacement example
To improve this you probably want to look at Integer.TryParse
to check if the result is actually an integer or not. Something like this:
Dim inputString As String = "Database_123456.bak"
Dim finalNumber As Integer
If Integer.TryParse(inputString.Replace("Database_", "").Replace(".bak", ""), finalNumber) Then
MessageBox.Show("The final number is " & finalNumber)
Else
MessageBox.Show("The string is not in the correct format")
End If
Also take care with upper and lower casing as replace is case sensitive
Upvotes: 2