Retrieve everything after a split in string VB.net - 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))

Related

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

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"

How can I seperate the values in the textbox to show in different labels using button?

i want to be able to separate the values in a textbox and display the separated values in different labels using a button
this is what i want to happen:
input "Ac2O3" on textbox
Be able to separate "Ac", "2", "O", and "3".
Show the separated values in different textboxes using a button
im using visual basic 2012
im sorry im still new to this
thanks in advance!!
You can access different character of the string with the index.
Dim input As String = "Ac2O3"
Dim part1 As String = input(0) & input(1)
Dim part2 As String = input(2)
Dim part3 As String = input(3)
Dim part4 As String = input(4)
If you don't know how to handle the button event or how to display text in a textbox, that would be different questions.
This code creates a structure called Element to make the results from the function clearer - add this to your main class that the function is going to be placed in. The main function takes a string as it's input and produced a list of structures of Element as it's output. There probably are shorter ways to do this, but I'm a fairly basic programmer who likes a puzzle - hope this helps - Dont forget to accept the answer by clicking on the tick. If you have any queries please dont hesitate to ask
Structure Element
Dim symbol As String
Dim elementCount As Int16
End Structure
Function ParseFormula(ByVal compoundString As String) As List(Of Element)
Dim tempParseFormula = New List(Of Element)
Dim firstLetter As String = "[A-Z]"
Dim secondLetter As String = "[a-z]"
Dim number As String = "[0-9]"
Dim tempElementCount As String = ""
Dim maxIndex As String = compoundString.Length - 1
Dim i As Integer = 0
Dim parsedElement As New Element
While i <= maxIndex
Dim tempChar As String = compoundString(i)
Select Case True
Case tempChar Like firstLetter
parsedElement.symbol = parsedElement.symbol & tempChar
Case tempChar Like secondLetter
parsedElement.symbol = parsedElement.symbol & tempChar
Case tempChar Like number
tempElementCount = tempElementCount & tempChar
End Select
If i = maxIndex Then
If Val(tempElementCount) = 0 Then
tempElementCount = 1
End If
parsedElement.elementCount = Val(tempElementCount)
tempParseFormula.Add(parsedElement)
parsedElement.symbol = ""
parsedElement.elementCount = 0
tempElementCount = ""
Exit While
End If
i += 1
If compoundString(i) Like firstLetter Then
If Val(tempElementCount) = 0 Then
tempElementCount = 1
End If
parsedElement.elementCount = Val(tempElementCount)
tempParseFormula.Add(parsedElement)
parsedElement.symbol = ""
parsedElement.elementCount = 0
tempElementCount = ""
End If
End While
Return tempParseFormula
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

Removing x-amount of letters in a string in VB.net

So in the database I have the following value:
"H-000000107"
I need to remove everything in the string in vb.net except the 107 at the end, the issue is, sometimes the last value can be longer eg.
"H-000001207"
In this case I need to return 1207 from the string. So the amount of letters and characters in front of the actual code (1207) is not always the same. Any help on this is appreciated!
this should do the work on all propabilities of after the H-
dim a as string = "H-000000107"
dim b as string = "H-000001207"
dim newval = -int(a.ToString.Split("H")(1)).tostring 'output 107
dim newval2 = -int(b.ToString.Split("H")(1)).tostring 'output 1207
Try this,
Dim xString = "H-000001207"
Dim xResult = string.empty
for i as integer = 0 to xString.length -1
if (xString.chars(i) = "H" orelse _
xString.chars(i) = "-" orelse _
(xString.chars(i) = "0" andalso not xResult = string.empty)) then
continue for
else
xResult &= xString.chars(i)
end if
next
MsgBox(val(xResult))
or May be a simple solution like this,
Dim xString = "H-000001207"
dim xRes = String.Empty
if xString.length > 3 then
xRes = val(xString.substring(2, xString.length-2))
end if
Hint (note that the result will be an empty string if you pass words like "H-"):
string result="";
string words = "H-000001207";
string[] split = words.Split(new Char[] { '-'});
if (split.GetUpperBound(0) == 1)
{
result = split[1].TrimStart('0');
}
else
result = "Error-Invalid format.";
Console.WriteLine(result);//is 1207
You can do this easily with Regex:
Dim pattern = "[1-9]\d*$"
Dim input = "H-000001207"
Dim result = Regex.Match(input, pattern)
Console.WriteLine(result.Value) '1207
Pattern explanation: Return the value at the end of the string ($) which starts by a digit other than zero ([1-9]) and is followed by 0 or more digits (\d*).

Strip all characters in textbox except letters and spaces

I am trying to strip all characters except letters and spaces but i am unable to do so. The code i currently have is below, how could i change that so it does allow spaces? At the moment it takes the text, strips it and it all becomes one big line of text.
Dim InputTxt As String = InputText.Text
Dim OutputTxt As System.Text.StringBuilder = New System.Text.StringBuilder()
For Each Ch As Char In InputTxt
If (Not Char.IsLetter(Ch)) Then
OutputTxt.Append(Ch)
Continue For
End If
Dim CheckIndex As Integer = Asc("a") - (Char.IsUpper(Ch) * -32)
Dim Index As Integer = ((Asc(Ch) - CheckIndex) + 13) Mod 26
OutputTxt.Append(Chr(Index + CheckIndex))
Next
OutputText.Text = (OutputTxt.ToString())
Dim output = New StringBuilder()
For Each ch As Char In InputTxt
If Char.IsLetter(ch) OrElse ch = " " Then
output.Append(ch)
End If
Next
OutputText.Text = output.ToString()
Not fully tested but a simple Regex should sustitute all of your code
Dim s = "ADB,12.#,,,122abC"
Dim result = Regex.Replace(s, "[^a-zA-Z ]+", "")
Console.WriteLine(result)
--> output = ADBabC
Here you can find the Regular Expression Pattern Reference
And here is a way to use LINQ to query the string.
Dim candidateText = "This is a test. Does it work with 123 and !"
Dim q = From c In candidateText
Where Char.IsLetter(c) OrElse c=" "
Select c
candidateText = String.Join("", q.ToArray)
Edit
Removed the Char.IsWhiteSpace in query to match the OP question.
I think graumanoz solution is best and doesn't use any unnecessary operations like ToList, but just for kicks:
Shared Function Strip(ByVal input As String)
Dim output = New StringBuilder()
input.ToList().Where(Function(x) Char.IsLetter(x) OrElse x = " ").ToList().
ForEach(Function(x) output.Append(x))
Return output.ToString()
End Function