vb.net how to find a range of digits in string - vb.net

I would like to split a String by a range of digits (0 to 20) and the letters should be .toLower
How can I define the range in my code?
I have tried to do it like this:("0","1","2","3")
Dim Tolerancevalueofext As String = "JS12"
Dim removenumber As String = Tolerancevalueofext.Substring(0, Tolerancevalueofext.IndexOf("0","1","2","3")).ToLower
But that is definitely wrong.

your request i quite unclear but here is a way to:
1. extract only numbers from string (using Regex).
2. extracting only letters from string that contains digits and converting them to small letters.
Private Sub Example()
Dim Tolerancevalueofext As String = "JS12"
' only numbers, output: "12"
Dim onlynumbers As String = extractNumberFromString(Tolerancevalueofext).ToString()
' only characters, output: "js"
Dim onlycharacters As String = String.Empty
For Each line As String In Tolerancevalueofext
If Not (IsNumeric(line)) Then
onlycharacters += line.ToLower()
End If
Next
End Sub
Public Shared Function extractNumberFromString(ByVal value As String) As Integer
Dim returnVal As String = String.Empty
Dim collection As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(value, "\d+")
For Each m As System.Text.RegularExpressions.Match In collection
returnVal += m.ToString()
Next
Return Convert.ToInt32(returnVal)
End Function
Output: onlynumbers = "12" onlycharacters = "js"

Related

How to Replace string and loop between commas with another string

can you help me how to get Index of the same string and replace it one by one with another string?
Here my example code :
For i As Integer = 0 To 10
Dim str As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
Dim replace As String = "efgh"
Dim value As String
value = str.Replace("abcd", replace)
TextBox4.AppendText(value)
Next
The value will be result : efgh,efgh,efgh,efgh,efgh...
How i can create the result like this :
efgh,abcd,abcd,abcd,abcd,abcd...
for the next loop it will be like this :
abcd,efgh,abcd,abcd,abcd,abcd...
for the next loop it will be like this :
abcd,abcd,efgh,abcd,abcd,abcd...
Thank you
There are lots of ways this could be done. One perhaps inefficient way would be to split the string at the commas, replace the appropriate item in the resulting array, and then join the array back up.
Dim str As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
Dim replace As String = "efgh"
For i As Integer = 0 To str.Count(Function(x) x = ","c)
Dim strParts = str.Split(","c)
strParts(i) = replace
Dim value As String = String.Join(",", strParts)
Console.WriteLine(value)
Next
Output:
efgh,abcd,abcd,abcd,abcd,abcd,abcd,abcd
abcd,efgh,abcd,abcd,abcd,abcd,abcd,abcd
abcd,abcd,efgh,abcd,abcd,abcd,abcd,abcd
abcd,abcd,abcd,efgh,abcd,abcd,abcd,abcd
abcd,abcd,abcd,abcd,efgh,abcd,abcd,abcd
abcd,abcd,abcd,abcd,abcd,efgh,abcd,abcd
abcd,abcd,abcd,abcd,abcd,abcd,efgh,abcd
abcd,abcd,abcd,abcd,abcd,abcd,abcd,efgh
As #Mark mentioned there are lots of ways this could be done. One of this ways to add and remove ranges in a string is to use the StringBuilder.
Imports System.Text
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i As Integer = 0 To 35 Step 5
Dim sDefaultString As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
Dim sbText = New StringBuilder(sDefaultString)
sbText.Remove(i, 4)
sbText.Insert(i, "efgh")
TextBox1.AppendText(sbText.ToString & vbNewLine)
Next
End Sub
End Class

Retrieve everything after a split in string VB.net

I'm needing to return the value of a string after it's been split in VB.Net.
The string will be something along the lines of:
someexpression1 OR someexpression2 OR someexpression3 OR someexpression4 OR someexpression5
The string can't contain more than 3 of these expressions so I need to retrieve everything after someexpression3.
After the split I would need the following "OR someexpression4 OR someexpression5", the full string will always be different lengths so I need something dynamic in order to capture the last part of the string.
Without further information on how danymic your splitting should be the following code will cover your requirement:
'Some UnitTest
Dim toSplit As String = "someexpression1 OR someexpression2 OR someexpression3 OR someexpression4 OR someexpression5"
Dim actual = GetLastExpressions(toSplit)
Dim expected = "OR someexpression4 OR someexpression5"
Assert.AreEqual(expected, actual)
toSplit = "requirement OR is OR weird"
actual = GetLastExpressions(toSplit)
expected = ""
Assert.AreEqual(expected, actual)
'...
Private Function GetLastExpressions(expression As String, Optional splitBy As String = "OR", Optional numberToSkip As Integer = 3)
Dim expr As String = ""
Dim lExpressions As IEnumerable(Of String) = Nothing
Dim aSplit = expression.Split({expression}, StringSplitOptions.None)
If aSplit.Length > numberToSkip Then
lExpressions = aSplit.Skip(numberToSkip)
End If
If lExpressions IsNot Nothing Then
expr = splitBy & String.Join(splitBy, lExpressions)
End If
Return expr
End Function
Spoke to a friend of mine who suggested this and it works fine;
Dim sline As String = MyString
Dim iorcount As Integer = 0
Dim ipos As Integer = 1
Do While iorcount < 17
ipos = InStr(ipos, sline, "OR")
ipos = ipos + 2
iorcount = iorcount + 1
Loop
MsgBox(Mid(sline, ipos))

Select the first 2 Characters of each word on String

I created the following function, but have not been able to finish. I want to return the first 2 characters of each word in the string. Here is what I have so far:
Function SelectWords(ByVal text As String, ByVal maxWords As Integer) As String
If String.IsNullOrEmpty(text) Then Return String.Empty
If maxWords <= 0 Then Return String.Empty
Dim words As String() = text.Split(" "c)
Return String ''I am stuck here
End Function
You did not describe the purpose of maxwords, nor what to do with a. The loop part:
Dim words = str.Split(" "c)
Dim ret As New StringBuilder ' in case it is a long string
For Each w As String In words
If w.Length > 1 Then
ret.Append(w.Substring(0, 2))
Else
' decide if you want 1
End If
Next
return ret.toString
The code you have doesn't do anything that you describing .. Try this function instead.
Function SelectWords(ByVal text As String, ByVal maxWords As Integer) As String
Dim collection As MatchCollection = Regex.Matches(text, "(\w{2})\w*\b")
Dim output As New System.Text.StringBuilder
Dim counter As Integer = 0
For Each M As Match In collection
output.Append(M.Groups(1).Value)
counter += 1
If counter = maxWords Then
Exit For
End If
Next
Return output.ToString
End Function

Getting the character that inside the brackets

This is my string:
Dim value as string = "IR_10748(1).jpg"
How can I get this number 1 into another variable? I am thinking to use split.
How I can use to get this value in vb.net?
See String.Substring(Integer, Integer) and String.IndexOf(String).
Dim value As String = "IR_10748(1).jpg"
Dim startIndex As Integer = value.IndexOf("(") + 1
Dim length As Integer = value.IndexOf(")") - startIndex
Dim content As String = value.Substring(startIndex, length)
Regular expressions might be cleaner. This should work:
dim Result as string = Regex.Match(value, "(?<=\().*(?=\))").Value
It'll extract one or more characters contained between the parentheses.
Try this:
Dim value as String = "IR_10748(1).jpg"
Dim splitStrings() as String
'Split on either opening or closing parenthesis -
'This will give 3 strings - "IR_10748","1",".jpg"
splitStrings = value.Split(New String() {"(",")"}, StringSplitOptions.None)
'Parse as integer if required
Dim i as Integer
i = Integer.Parse(splitStrings(1))
Demo
It's not the prettiest, but this gets "1" using Remove and Split :
Dim value as String = "IR_10748(1).jpg"
Dim num As String = value.Remove(0, value.IndexOf("(") + 1).Split(")")(0)
That gives num = "1"
You can get the number more reliably than using String.Split. You'll want to use LastIndexOf to get the final opening parenthesis just in case you have a filename like "a(whatever)(1).ext", and you should inspect the filename without its extension, in case you have a filename like "a(1).(9)":
Dim value As String = "IR_10748(1).jpg"
Dim fn = Path.GetFileNameWithoutExtension(value)
Dim lastOpen = fn.LastIndexOf("(")
If lastOpen >= 0 Then
Dim length = fn.IndexOf(")", lastOpen + 1) - lastOpen - 1
If length >= 1 Then
Dim numAsString = fn.Substring(lastOpen + 1, length)
Console.WriteLine(numAsString)
ElseIf length = 0 Then
' do something if required
Console.WriteLine("No number in the parentheses.")
Else
' do something if required
Console.WriteLine("No closing parenthesis.")
End If
Else
' do something if required
Console.WriteLine("No opening parenthesis.")
End If

generate random string

well i know that there are a lot of these threads but im new to vb.net yet i cant edit the sources given to make what i really want
so i want a function that will generate random strings which will contain from 15-32 characters each and each of them will have the following chars ( not all at the same string but some of them ) :
A-Z
a-z
0-9
here is my code so far
Functon RandomString()
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 8
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
Next
return sb.ToString()
End Function
Change the string to include the a-z characters:
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Change the loop to create a random number of characters:
Dim cnt As Integer = r.Next(15, 33)
For i As Integer = 1 To cnt
Note that the upper boundary in the Next method is exclusive, so Next(15, 33) gives you a value that can range from 15 to 32.
Use the length of the string to pick a character from it:
Dim idx As Integer = r.Next(0, s.Length)
As you are going to create random strings, and not a single random string, you should not create the random number generator inside the function. If you call the function twice too close in time, you would end up with the same random string, as the random generator is seeded using the system clock. So, you should send the random generator in to the function:
Function RandomString(r As Random)
So, all in all:
Function RandomString(r As Random)
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Dim sb As New StringBuilder
Dim cnt As Integer = r.Next(15, 33)
For i As Integer = 1 To cnt
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
return sb.ToString()
End Function
Usage example:
Dim r As New Random
Dim strings As New List<string>()
For i As Integer = 1 To 10
strings.Add(RandomString(r))
Next
Try something like this:-
stringToReturn&= Guid.NewGuid.ToString().replace("-","")
You can also check this:-
Sub Main()
Dim KeyGen As RandomKeyGenerator
Dim NumKeys As Integer
Dim i_Keys As Integer
Dim RandomKey As String
''' MODIFY THIS TO GET MORE KEYS - LAITH - 27/07/2005 22:48:30 -
NumKeys = 20
KeyGen = New RandomKeyGenerator
KeyGen.KeyLetters = "abcdefghijklmnopqrstuvwxyz"
KeyGen.KeyNumbers = "0123456789"
KeyGen.KeyChars = 12
For i_Keys = 1 To NumKeys
RandomKey = KeyGen.Generate()
Console.WriteLine(RandomKey)
Next
Console.WriteLine("Press any key to exit...")
Console.Read()
End Sub
Using your function as a guide, I modified it to:
Randomize the length (between minChar & maxCharacters)
Randomize the string produced each time (by using the static Random)
Code:
Function RandomString(minCharacters As Integer, maxCharacters As Integer)
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Static r As New Random
Dim chactersInString As Integer = r.Next(minCharacters, maxCharacters)
Dim sb As New StringBuilder
For i As Integer = 1 To chactersInString
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
Return sb.ToString()
End Function
Try this out:
Private Function RandomString(ByRef Length As String) As String
Dim str As String = Nothing
Dim rnd As New Random
For i As Integer = 0 To Length
Dim chrInt As Integer = 0
Do
chrInt = rnd.Next(30, 122)
If (chrInt >= 48 And chrInt <= 57) Or (chrInt >= 65 And chrInt <= 90) Or (chrInt >= 97 And chrInt <= 122) Then
Exit Do
End If
Loop
str &= Chr(chrInt)
Next
Return str
End Function
You need to change the line For i As Integer = 1 To 8 to For i As Integer = 1 To ? where ? is the number of characters long the string should be. This changes the number of times it repeats the code below so more characters are appended to the string.
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
My $.02
Dim prng As New Random
Const minCH As Integer = 15 'minimum chars in random string
Const maxCH As Integer = 35 'maximum chars in random string
'valid chars in random string
Const randCH As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
Private Function RandomString() As String
Dim sb As New System.Text.StringBuilder
For i As Integer = 1 To prng.Next(minCH, maxCH + 1)
sb.Append(randCH.Substring(prng.Next(0, randCH.Length), 1))
Next
Return sb.ToString()
End Function
please note that the
r.Next(0, 35)
tend to hang and show the same result Not sure whay; better to use
CInt(Math.Ceiling(Rnd() * N)) + 1
see it here Random integer in VB.NET
I beefed up Nathan Koop's function for my own needs, and thought I'd share.
I added:
Ability to add Prepended and Appended text to the random string
Ability to choose the casing of the allowed characters (letters)
Ability to choose to include/exclude numbers to the allowed characters
NOTE: If strictly looking for an exact length string while also adding pre/appended strings you'll need to deal with that; I left out any logic to handle that.
Example Usages:
' Straight call for a random string of 20 characters
' All Caps + Numbers
String_Random(20, 20, String.Empty, String.Empty, 1, True)
' Call for a 30 char string with prepended string
' Lowercase, no numbers
String_Random(30, 30, "Hey_Now_", String.Empty, 2, False)
' Call for a 15 char string with appended string
' Case insensitive + Numbers
String_Random(15, 15, String.Empty, "_howdy", 3, True)
.
Public Function String_Random(
intMinLength As Integer,
intMaxLength As Integer,
strPrepend As String,
strAppend As String,
intCase As Integer,
bIncludeDigits As Boolean) As String
' Allowed characters variable
Dim s As String = String.Empty
' Set the variable to user's choice of allowed characters
Select Case intCase
Case 1
' Uppercase
s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Case 2
' Lowercase
s = "abcdefghijklmnopqrstuvwxyz"
Case Else
' Case Insensitive + Numbers
s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
End Select
' Add numbers to the allowed characters if user chose so
If bIncludeDigits = True Then s &= "0123456789"
Static r As New Random
Dim chactersInString As Integer = r.Next(intMinLength, intMaxLength)
Dim sb As New StringBuilder
' Add the prepend string if one was passed
If String.IsNullOrEmpty(strPrepend) = False Then sb.Append(strPrepend)
For i As Integer = 1 To chactersInString
Dim idx As Integer = r.Next(0, s.Length)
sb.Append(s.Substring(idx, 1))
Next
' Add the append string if one was passed
If String.IsNullOrEmpty(strAppend) = False Then sb.Append(strAppend)
Return sb.ToString()
End Function