How to strip a string of all alpha's? - vb.net

Dim phoneNumber As String = "077 47578 587(num)"
How do i strip the above string off every character which isnt a number. So only the numbers are left and then check to make sure it is 11 characters long?

dim number as string = Regex.Replace(phoneNumber,"[^0-9]","")
if number.length = 11 then
'valid number
else
'not valid
end if

You could loop on each character and check if it is a digit. While looping, check that the number of accepted characters (digits) is less than 11.
or
use a regex to remove all the alpha but you still will have to count at the end ....

Dim phoneNumber As String = "077 47578 587(num)"
Dim newPhoneNumber = String.Empty
For i = 0 To phoneNumber.Length - 1
If IsNumeric(phoneNumber(i)) Then
newPhoneNumber += phoneNumber(i)
End If
Next
Dim valid = newPhoneNumber.Length = 11

One possible solution is to treat the string as a character array, then retrieve only those characters with ascii codes within the paramaeters you define.
Ascii codes can be found at a resource such as: http://www.bolen.net/html/misc/ASCII-codes.html
Alternatively, you could use a regular expression to retrieve only the characters you want. My regex isn't so hot, so I can't give an example :)

Related

How do I convert integer to 4-digit hex string?

I need to convert a 2-byte signed integer into a string of it's hex equivalent, but I need the string to be 4 characters. I've tried the Hex() function but when I convert 0 or say, 10, the result is 0 or A. I need the result to be 0000 or 000A. Any tips or advice?
It is just
Dim hexS As String = i.ToString("X4")
This is well explained in the The Hexadecimal (X) Format specifier.
The 4 after the X specifies how many chars you want in the output and if there are not enough chars, the missing ones are supplied as an appropriate number of "0".
Since you also tagged the question VBA, here is a VBA way to do it
Right("0000" & Hex(i), 4)
Use
Dim i As Integer = 10
Dim hexS As String = i.ToString("X4")
If you are deadset on using Hex as opposed to string formatting then you could use:
Dim Number As Integer
Dim Output As String
Number = 10
Output = ("000" & Hex(Number))
Output = Output.Substring(Output.Length - 4, 4)
Console.WriteLine(Output)
Alternatively make use of string formatting for numbers as so:
Output = Number.ToString("X4")
Console.WriteLine(Output)
The output in both cases with be 000A.
The VB way
Format(i, "X4")
or
Hex(i).PadLeft(4, "0"c)
In Visual Studio 2015:
s = $"{i:X4}"

Get substring until first numeric character

like my title already explained, I want to get a substring of a string (who contains a address) and I would like to have only the street..
It's not possible to only take the text (non-numeric) chars, because then the box will remain.
It's not possible to take substring till first space, because the streetname can contain a space..
For example 'developerstreet 123a' -> would like to have 'developerstreet'
The 'a' is a box number of the house, which I'm not interested in..
How can I do this in VB.NET?
Parsing addresses is notoriously difficult, so I caution you to make sure that you a very deliberate about the choices you make. I would strongly recommend reviewing the documentation provided by the postal service. If these are US addresses, you should start by looking at the USPS Publication 28.
However, to answer your specific question, you can find the index of the first numeric character in a string by using the Char.IsDigit method. You may also want to take a look at the Char.IsNumber method, but that's probably more inclusive than what you really want. For instance, this will get the index of the first numeric character in the input string:
Dim index As Integer = -1
For i As Integer = 0 to input.Length - 1
If Char.IsDigit(input(i)) Then
index = i
Exit For
End If
Next
However, for complex string parsing, like this, I would suggest learning Regular Expressions. Getting the non-numeric portion at the beginning of a string becomes trivial with RegEx:
Dim m As Match = Regex.Match(input, "^\D+")
If m.Success Then
Dim nonNumericPart As String = m.Value
End If
Here is the meaning of the regular expression in the above example:
^ - The matching string must start at the beginning of the line
\D - Any non-numeric character
+ - One or more times
try this:
Private Sub MyFormLoad(sender As Object, e As EventArgs) Handles Me.Load
Dim str As String = "developerstreet 123a"
Dim index As Integer = GetIndexOfNumber(str)
Dim substr As String = str.Substring(0, index)
MsgBox(substr)
End Sub
Public Function GetIndexOfNumber(ByVal str As String)
For n = 0 To str.Length - 1
If IsNumeric(str.Substring(n, 1)) Then
Return n
End If
Next
Return -1
End Function
output will be: developerstreet
text.Substring(0, text.IndexOfAny("0123456789"))

how to i create a Username shortener?

I have an AD username called "lastname-132" in Textbox1, this string is 12 long, so i want to add the username in to Textbox2, but shortened, in the textbox2 i only have a string length of only 10 available due to other tools this program is using, so i don't want to convert it all the time manually and want to just convert it automatically with a onleave event.
Anyone any idea how to write this?
So the End Result should look like this.
'String length can be 20 max.
Textbox1.Text = "lastname-123"
'some code to convert it to this:
'String length 10 max. Numbers and the "-" should stay the same, but remove letters if necessary.
Textbox2.Text = "lastna-123"
Here's the concept:
Split string based on '-' into 2 strings
In the example above: 'lastname' and '123'.
Check the length of the first string and cut if it is too long
the program checks 'lastname' and finds that it is too long, then
cuts it into 'lastna'
Combine 'lastna' and '123' back into a string
I hope this helps
Without more information, this will assume that there can be multiple hyphens, the number can be of variable length, and you can change the maximum length of the string by changing one variable.
Dim username As String = "lastname-123"
Dim max As Integer = 10
Dim lindex As Integer = username.LastIndexOf("-")
Dim numberLength As Integer = username.Length - lindex
Dim number As String = username.Substring(lindex)
Dim justName As String = username.Substring(0, lindex)
If justName.Length + numberLength >= max Then
username = justName.Substring(0, max - numberLength) & number
End If
If you are concentrating only on the restriction of length of characters to be accepted then you can use
Maxlength
property of the Textbox.
Ex: Maxlength="10"
restricts the Textbox to accept only 10 characters.
Try to make it fit with for example substring manipulation. See http://msdn.microsoft.com/en-us/library/dd789093.aspx for more info.

VB determining values within a string

I am looking for assistance with my program. I have a user enter 6 digits; of these the input must be alpha-numeric. I have already done the TryParse method for the numbers, but I am looking for validation that the string contains an alpha.
I am aware you must use ASC but am unsure both on how to develop a range say Asc((Chr(65) <= Chr(90))) (between A-Z) and also to say (IF my input contains any of these values within the 6 characters, to return true. I keep getting an overload resolution and wish to know how to properly code so the variables are accurate.
This is a great place to use a regular expression
Dim input = ...
If Regex.IsMatch(input, "^\w+$") AndAlso input.Length = 6 Then
' It's a match
Else
' It's not a match
End If
This will match any string which consists only of letters that has length equal to 6
You can iterate through each char and check if it's a letter. If so, set a flag to true.
Dim containsAlpha Boolean = False
For i As Integer = 0 To input.Length - 1
If Char.IsLetter(input(i)) Then
containsAlpha = True
Exit For
End If
Next
Char.IsLetter will match Unicode alphabetic letters, so not just Latin A-Z (which may or may not be what you actually want).

splitting a string to access integer within it

i have a string "<PinX F='53mm'></PinX>", I want to access the 53 within the string and do some addition to it and then add the answer back into that string. I've been thinking about this and wasn't sure whether this can be done with regular expression or not? Can anybody help me out.
thanks
Yes, you can use a regular expression. This will get the digits, parse them to a number, add one to it, and put it back in the string (that is, the result is actually a new string as strings are immutable).
string s = Regex.Replace(
input,
#"(\d+)",
m => (Int32.Parse(m.Groups[1].Value) + 1).ToString()
);
Take a look at the HTML Agility Pack.
A regular expression looks like a good fit for this particular problem:
\d+
Will match one or more digits.
Int32.Parse(Regex.Match("<PinX F='53mm'></PinX>", #"\d+").Value)
Will return 53.
In this single case yes. "'(.*?)' then access the first group, but if this is part of a larger xml regular expressions should not be used. You should utilize the xml parser build into .net find the attribute with xsd and get the value.
Alternatively, here's a small routine...
' Set testing string
Dim s As String = "<PinX F='53mm'></PinX>"
' find first occurence of CHAR ( ' )
Dim a As Integer = s.IndexOf("'")
' find last occurence of CHAR ( ' )
Dim b As Integer = s.LastIndexOf("'")
' get substring "53mm" from string
Dim substring As String = s.Substring(a, b - a)
' get integer values from substring
Dim length As Integer = substring.Length
Dim c As Char = Nothing
Dim result As String = Nothing
For i = 1 To length - 1
c = substring.Chars(i)
If IsNumeric(c) Then
result = result & c
End If
Next
Console.WriteLine(Int32.Parse(result))
Console.ReadLine()