get string after and before word - vb.net

i need to get a set of values after certain 14 length of a string and before the last 5 stringss.
eg:
Theboyisgoingt9123holdi: so i need to get the value 9123
iamfullofmeats89holdi: i need to extract value 89
so the algorithm here is, i am trying to extract the values that comes after the 14th length of the string and just before the last 5 characters of the same string.
its always whats between 14th and last 5 characters.
i am coding in vb.net.
any ideas is great appreciated.

Dim ResultString As String
ResultString = Regex.Match(SubjectString, "(?<=^.{14}).*(?=.{5}$)").Value
will give you the characters from the 15th until the 6th-to-last character in the string. It is assumed that there are no newlines in the string. If there are, and you want to treat them just like any other character, use the option RegexOptions.Singleline as an additional parameter to Regex.Match().
Explanation:
(?<=^.{14}): Match a position that is after the 14th character in the string.
.*: Match anything until...
(?=.{5}$): ...the position before the last 5 characters in the string.

I too would go with a regex. This is how I would do it:
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim str As String = "Theboyisgoingt9123holdi"
Dim m As Match = Regex.Match(str, "^.{14}(.+).{5}$")
If m.Success Then
Console.WriteLine(m.Groups(1).Value)
End If
End Sub
End Module

This is a great place to use a regular expression
Function GetNumber(ByVal str As String) As String
Dim match = Regex.Match("\d+", str)
if math.Sucess then
Return match.Value
Else
Return String.Empty
End If
End Function

Related

vb.net if statement between range of numbers

is there a way in vb.net that i can run an if statement to say if a variable starts with 07 then between 1-9
i know i could do this using substring which would work but it would make the if statement rather large
number_called.Substring(0, 3) = "071" or number_called.Substring(0, 3) = "072"
and so on up to 079 but can i create a shorter if statement for the whole range?
This would do it
Private Function CheckNumber(myNumber As String) As Boolean
Dim regex As Regex = New Regex("^07[1-9]]")
Dim match As Match = regex.Match(myNumber)
Return match.Success
End Function
Just call CheckNumber("071") or CheckNumber(number_called)
Remember to import the references Imports System.Text.RegularExpressions
Updated Expression, thank you Veeke
You could use String.StartsWith("07") and check the last character of the String - it must be a number and not 0 like this:
If str.Length = 3 And str.StartsWith("07") And Char.IsNumber(str(2)) And str(2) <> "0" Then
End If
If you know that it will always start with 3 numbers you can parse it
Dim num = Int32.Parse(number_called.Substring(0, 3))
Dim Valid= num>69 and num<80
If you dont know if it will start with 3 numbers, surround it with a TryCatch
Small correction on Malcor's post, which doesn't check if it begins with '07' (just if it contains '07'):
Private Function CheckNumber(myNumber As String) As Boolean
Dim regex As Regex = New Regex("^07[1-9]")
Dim match As Match = regex.Match(myNumber)
Return match.Success
End Function
You could use StartsWith coupled with a Select Case if you are sure it is always a numeric string:
If number_called.StartsWith("07") Then
Select Case CInt(number_called.SubString(2, 1))
Case 1 to 9
'it matched
Case Else
'it didn't match
End Select
End If

Validating a string

I am trying to write a program where the user inputs a telephone number and a message is displayed if it contains a letter.
Module Module1
Sub Main()
Dim TelNumber As String
Dim Character As String
TelNumber = Console.ReadLine()
For Number = 0 To TelNumber.Length - 1
Character = TelNumber.Substring(Number)
If Integer.TryParse(Character, 0) <> 0 Then
Console.WriteLine("It cannot contain a letter")
Exit For
End If
Next
Console.ReadLine()
End Sub
End Module
However with this code even it only works properly if the string contains less than 11 charcaters, after that even if it does not contain any letters it still displays the message. How do I fix this? Also I don't understand what the second parameter of the Integer.TryParse function represents?
TelNumber.Substring(Number) does not just the Numberth character of the string.
It returns the string with Number characters stripped off its beginning.
Thus, in the first step of the loop, TelNumber.Substring(0) returns the whole string.
Then, Integer.TryParse() fails with integer overflow with long string.
Hint: simple string validation is a task for regular expressions.
With regular expressions it will also be very easy to extend tel.number format to something like +4915771828000 or 12-34-56.
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim telNumber As String = Console.ReadLine()
Dim telValidationRegex As Regex = New Regex("^\d+$")
If NOT telValidationRegex.Match(telNumber).Success Then
Console.WriteLine("Wrong telephone number format")
End If
Console.ReadLine()
End Sub
End Module
I don't have a compiler handy, but I can tell you what I think this should look like. First let's look at Int32.TryParse's documentation
result
Type: System.Int32
When this method returns, contains the 32-bit signed integer value equivalent of the number contained in s, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is null or String.Empty, is not of the correct format, or represents a number less than MinValue or greater than MaxValue. This parameter is passed uninitialized.
So, the second parameter is supposed to be an integer variable that contains the result of trying to parse the string.
Then, let's look at substring
startIndex
Type: System.Int32
The zero-based starting character position of a substring in this instance.
So what you're doing isn't looking at each character and trying to convert it to an integer. It's looking at the whole number, and trying to convert that to an integer. Then the whole number, except for the first character, and trying to convert that to a number. And so on.
I suspect you'll find that Int32 can only store numbers about 10 digits long (2^32, or 4294967296)
What you want to do is look at each character, something like this.
Module Module1
//Warning, did not try to compile
Sub Main()
Dim TelNumber As String
Dim Character As String
TelNumber = Console.ReadLine()
For Number = 0 To TelNumber.Length - 1
Character = TelNumbert(Number)
Dim OutputNumber as Integer
If Not Integer.TryParse(Character, OutputNumber) Then
Console.WriteLine("It cannot contain a letter")
Exit For
End If
Next
Console.ReadLine()
End Sub
End Module

Remove the character alone from the string

My code retrieves the data from various resources .
And output will be like below
UNY4/4/2010
hds04/5/2010
saths04/22/2013
But I want the output like this
4/4/2010
4/5/2010
04/22/2013
Is there any way to do this ?
You need to use a regular expression that finds all uppercase and lowercase characters and replaces them with a blank, like this:
Dim rgx As New Regex("[a-zA-Z]")
str = rgx.Replace(str, String.Empty)
An alternate solution is to look for the first numeric digit, then discard all text before that.
Function GetDate(data As String) As Date
Dim indexFirstNum As Integer = data.IndexOfAny("0123456789".ToCharArray())
Dim datePortion As String = data.Substring(indexFirstNum)
Return Date.Parse(datePortion)
End Function

How to filter anything but numbers from a string

I want to filter out other characters from a string as well as split the remaining numbers with periods.
This is my string: major.number=9minor.number=10revision.number=0build.number=804
and this is the expected output: 9.10.0.804
Any suggestions?
As to my comment, if your text is going to be constant you can use String.Split to remove the text and String.Join to add your deliminators. Quick example using your string.
Sub Main()
Dim value As String = "major.number=9minor.number=10revision.number=0build.number=804"
Dim seperator() As String = {"major.number=", "minor.number=", "revision.number=", "build.number="}
Console.WriteLine(String.Join(".", value.Split(seperator, StringSplitOptions.RemoveEmptyEntries)))
Console.ReadLine()
End Sub
If your string does not always follow a specific pattern, you could use Regex.Replace:
Sub Main()
Dim value as String = "major.number=9minor.number=10revision.number=0build.number=804"
Dim version as String = Regex.Replace(value, "\D*(\d+)\D*", "$1.") ' Run the regex
version = version.Substring(0, version.Length - 1) ' Trim the last dot
End
Note you should Imports System.Text.RegularExpressions.

How to remove a character from at string at certain position from the end?

I have a string, for example:
Dim str as string = xxxxxxxxxxxxxxxxxxxx£xxx£xxxx**£**xxxxxxxxxx
I want to remove £ surrounded from * which is always at a certain position (11th for instance) from the end. The whole string is a long one, always change in size and cannot be counted from the start. I cannot use Replace as well, there may be same characters at other positions that I do not wish to remove.
Solution:
Dim rst As String = str.Remove(str.Length - 11, 1)
Edit: Whoops, I dunno what I was thinking on that first part.
The correct version of the first part would be:
str = str.Substring(0, str.Len -13) + str.Substring(str.Len-11);
There also may be an overload for the String.Delete function that allows you to use a negative number to represent the number of characters from the end of the string -- I know that the C# equivalent does.
If its always going to be the 11th character from the end you can do this...
Dim strTargetString As String = "xxxYxxxxxxxxxx"
Dim strTargetString2 As String = "xxxxxxxYxxxxxxxxxx"
Dim strResult As String = Mid(strTargetString, 1, (Len(strTargetString) - 11)) & Microsoft.VisualBasic.Right(strTargetString, 10)
Dim strResult2 As String = Mid(strTargetString2, 1, (Len(strTargetString2) - 11)) & Microsoft.VisualBasic.Right(strTargetString, 10)
Note that String.SubString is a more modern approach than Mid, but I use it out of preference and example.
This is fairly straightforward with a regular expression replacement operation using look-ahead:
Dim str as String = "xxxxxxxxxxxxxxxxxxxx£xxx£xxxx£xxxxxxxxxx"
Dim str2 as String = Regex.Replace(str, "£(?=.{10}$)", String.Empty)
This will target a single character followed by any ten characters then the end of the string and replace it with the String.Empty value (or just "" if you'd prefer).