Would someone help me with this please?
In vb.net (VS2013):
a string is in the format: char12345 (6789).jpg
trim to the string to: char12345.jpg
Basically, I need to trim off the middle part: the space and everything in parentheses (including the parentheses).
will VB's trim function work? or I need to use RegEx...
Many thanks in advance!
You don't need regex, you could remove the parantheses also with pure string methods:
Dim path = "char12345 (6789).jpg"
Dim ext = IO.Path.GetExtension(path)
Dim fn = IO.Path.GetFileNameWithoutExtension(path)
Dim index = fn.IndexOf("(")
If index >= 0 Then fn = fn.Remove(index).Trim()
path = String.Format("{0}{1}", fn, ext)
Presumes that they are always directly before the extension or that the part behind them can also be removed. Otherwise it's getting a little bit more complicated:
Dim index = fn.IndexOf("(")
If index >= 0 Then
Dim endindex = fn.LastIndexOf(")", index)
If endindex >= 0 Then
fn = fn.Remove(index).Trim() & fn.Substring(endindex + 1)
Else
fn = fn.Remove(index).Trim()
End If
End If
Given your input, you can accomplish this with Split
Dim str as String = "char12345 (6789).jpg"
Console.Write(str.Split(" ")(0) & "." & str.Split(".")(1))
Related
I have this String:
"[" & vbCrLf & " ""APPLE""" & vbCrLf & "]"
The only thing I need is APPLE.
I tried a few options with Split, Trim, Left and more, but they didn't work very well.
Thank you very much!
As the comments above have said, there's not enough information to give an answer without making assumptions, which could be wrong. I've assumed you want to extract the value between two quotation marks, regardless of what else is before or after.
If that's what you want, try this:
Dim Result As String = Nothing
Dim source As String = $"[{vbCrLf}""Apple""{vbCrLf}]"
Dim FirstQuote As Integer = source.IndexOf("""")
If FirstQuote > -1 And source.Length > FirstQuote Then
Dim SecondQuote As Integer = source.IndexOf("""", FirstQuote + 1)
If SecondQuote > FirstQuote Then
Result = source.Substring(FirstQuote + 1, SecondQuote - FirstQuote - 1)
End If
End If
If Result Is Nothing Then
'Handle Invalid Format
Else
'Process Result
End If
You would need to modify that so that you passed your source string, rather than defining it in the code. If you wanted to extract multiple words from a single string in the same format, just set FirstQuote = SecondQuote + 1, check that doesn't exceed the length of the source string and loop through again.
I am going to assume that you probably just need to get the first occurance of a string (in this case "apple") within square-brackets using split and so:
Dim AppleString As String = "This is an [Apple] or etc [...]"
console.WriteLine(AppleString.split("[")(1).split("]")(0).trim())
⚠️ This is not a solution for all purposes !!!
I have Textboxes Lines:
{ LstScan = 1,100, DrwR2 = 0000000043 }
{ LstScan = 2,200, DrwR2 = 0000000041 }
{ LstScan = 3,300, DrwR2 = 0000000037 }
I should display:
1,100
2,200
3,300
this is a code that I can't bring to a working stage.
Dim data As String = TextBox1.Lines(0)
' Part 1: get the index of a separator with IndexOf.
Dim separator As String = "{ LstScan ="
Dim separatorIndex = data.IndexOf(separator)
' Part 2: see if separator exists.
' ... Get the following part with Substring.
If separatorIndex >= 0 Then
Dim value As String = data.Substring(separatorIndex + separator.Length)
TextBox2.AppendText(vbCrLf & value)
End If
Display as follows:
1,100, DrwR2 = 0000000043 }
This should work:
Function ParseLine(input As String) As String
Const startKey As String = "LstScan = "
Const stopKey As String = ", "
Dim startIndex As String = input.IndexOf(startKey)
Dim length As String = input.IndexOf(stopKey) - startIndex
Return input.SubString(startIndex, length)
End Function
TextBox2.Text = String.Join(vbCrLf, TextBox1.Lines.Select(AddressOf ParseLine))
If I wanted, I could turn that entire thing into a single (messy) line... but this is more readable. If I'm not confident every line in the textbox will match that format, I can also insert a Where() just before the Select().
Your problem is you're using the version of substring that takes from the start index to the end of the string:
"hello world".Substring(3) 'take from 4th character to end of string
lo world
Use the version of substring that takes another number for the length to cut:
"hello world".Substring(3, 5) 'take 5 chars starting from 4th char
lo wo
If your string will vary in length that needs extracting you'll have to run another search (for example, searching for the first occurrence of , after the start character, and subtracting the start index from the newly found index)
Actually, I'd probably use Split for this, because it's clean and easy to read:
Dim data As String = TextBox1.Lines(0)
Dim arr = data.Split()
Dim thing = arr(3)
thing now contains 1,100, and you can use TrimEnd(","c) to remove the final comma
thing = thing.TrimEnd(","c)
You can reduce it to a one-liner:
TextBox1.Lines(0).Split()(3).TrimEnd(","c)
I'm a programing student, so I've started with vb.net as my first language and I need some help.
I need to know how I delete excess white spaces between words in a sentence, only using these string functions: Trim, instr, char, mid, val and len.
I made a part of the code but it doesn't work, Thanks.
enter image description here
Knocked up a quick routine for you.
Public Function RemoveMyExcessSpaces(str As String) As String
Dim r As String = ""
If str IsNot Nothing AndAlso Len(str) > 0 Then
Dim spacefound As Boolean = False
For i As Integer = 1 To Len(str)
If Mid(str, i, 1) = " " Then
If Not spacefound Then
spacefound = True
End If
Else
If spacefound Then
spacefound = False
r += " "
End If
r += Mid(str, i, 1)
End If
Next
End If
Return r
End Function
I think it meets your criteria.
Hope that helps.
Unless using those VB6 methods is a requirement, here's a one-line solution:
TextBox2.Text = String.Join(" ", TextBox1.Text.Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries))
Online test: http://ideone.com/gBbi55
String.Split() splits a string on a specific character or substring (in this case a space) and creates an array of the string parts in-between. I.e: "Hello There" -> {"Hello", "There"}
StringSplitOptions.RemoveEmptyEntries removes any empty strings from the resulting split array. Double spaces will create empty strings when split, thus you'll get rid of them using this option.
String.Join() will create a string from an array and separate each array entry with the specified string (in this case a single space).
There is a very simple answer to this question, there is a string method that allows you to remove those "White Spaces" within a string.
Dim text_with_white_spaces as string = "Hey There!"
Dim text_without_white_spaces as string = text_with_white_spaces.Replace(" ", "")
'text_without_white_spaces should be equal to "HeyThere!"
Hope it helped!
I need to get a certain character from a long string line, that occurs more than once. This is what the string looks like:
<Press T><Press Left><Press A><Press C><Press P><Press U><Press G><Press P><Press NumPad7><Press NumPad7><Press A>
I need to loop through each set of <>'s and get the info that is after each occurrence of the word Press. So in this case I would need the info T, Left, A, C, P, etc
I think this pure String-method approach is the most efficient, but it requires the format to be strict:
Dim text = "<Press T><Press Left><Press A><Press C><Press P><Press U><Press G><Press P><Press NumPad7><Press NumPad7><Press A>"
Dim allKeys As New List(Of String)
Dim pattern = "Press "
Dim index = text.IndexOf(pattern)
While index >= 0
index += pattern.Length
Dim endIndex = text.IndexOf(">", index)
If endIndex >= 0 Then
Dim nextKey = text.Substring(index, endIndex - index)
allKeys.Add(nextKey)
index = text.IndexOf(pattern, endIndex + 1)
Else
Exit While
End If
End While
Console.Write(String.Join(", ", allKeys))
Output: T, Left, A, C, P, U, G, P, NumPad7, NumPad7, A
Here is the Regex that returns all matches, you find the "key" that was pressed in the second group:
pattern = "<Press ([^>]+)>"
Dim regex = New Regex( pattern, RegexOptions.Compiled And RegexOptions.IgnoreCase)
For Each match As Match In regex.Matches(text)
Console.WriteLine(match.Groups(1))
Next
Assuming it's the same format all the time you can do this in one line. Regex would be better if there's a chance the format would be different (e.g. random number of whitespaces etc..)
Dim myString As String = "<Press T><Press Left><Press A><Press C><Press P><Press U><Press G><Press P><Press NumPad7><Press NumPad7><Press A>"
Dim character As String() = myString.Split(New String() {"<Press ", ">"}, StringSplitOptions.RemoveEmptyEntries)
RegEx, short for regular expressions, is an easy way to parse strings. This site Provides good information on using RegEx in .NET. It's how I learned. The site also provides good info on RegEx in general if you are not familiar.
Edit: RegEx expressions can be complicated to create. A great tool to help you out with that is Expresso. It'll help you create and test very complicated expressions with a minimal of fuss.
Dim s As String = "<Press T><Press Left><Press A><Press C><Press P><Press U><Press G><Press P><Press NumPad7><Press NumPad7><Press A>"
Dim ss() As String = s.Replace("<Press ", "").Split(">"c)
For i as integer = 0 to ss.count - 2
Debug.Print(ss(i))
Next
Output:
T
Left
A
C
P
U
G
P
NumPad7
NumPad7
A
Note that the array ss is one longer than the number of key presses due to the final ">" being treated as another separator by .split, you could always remove the final ">"
I have code below. How do I get strings inside brackets? Thank you.
Dim tmpStr() As String
Dim strSplit() As String
Dim strReal As String
Dim i As Integer
strWord = "hello (string1) there how (string2) are you?"
strSplit = Split(strWord, "(")
strReal = strSplit(LBound(strSplit))
For i = 1 To UBound(strSplit)
tmpStr = Split(strSplit(i), ")")
strReal = strReal & tmpStr(UBound(tmpStr))
Next
Dim src As String = "hello (string1) there how (string2) are you?"
Dim strs As New List(Of String)
Dim start As Integer = 0
Dim [end] As Integer = 0
While start < src.Length
start = src.IndexOf("("c, start)
If start <> -1 Then
[end] = src.IndexOf(")"c, start)
If [end] <> -1 Then
Dim subStr As String = src.Substring(start + 1, [end] - start - 1)
If Not subStr.StartsWith("(") Then strs.Add(src.Substring(start + 1, [end] - start - 1))
End If
Else
Exit While
End If
start += 1 ' Increment start to skip to next (
End While
This should do it.
Dim result = Regex.Matches(src, "\(([^()]*)\)").Cast(Of Match)().Select(Function(x) x.Groups(1))
Would also work.
This is what regular expressions are for. Learn them, love them:
' Imports System.Text.RegularExpressions
Dim matches = Regex.Matches(input, "\(([^)]*)\)").Cast(of Match)()
Dim result = matches.Select(Function (x) x.Groups(1))
Two lines of code instead of more than 10.
In the words of Stephan Lavavej: “Even intricate regular expressions are easier to understand and modify than equivalent code.”
Use String.IndexOf to get the position of the first opening bracket (x).
Use IndexOf again the get the position of the first closing bracket (y).
Use String.Substring to get the text based on the positions from x and y.
Remove beginning of string up to y+1.
Loop as required
That should get you going.
This may also work:
Dim myString As String = "Hello (FooBar) World"
Dim finalString As String = myString.Substring(myString.IndexOf("("), (myString.LastIndexOf(")") - myString.IndexOf("(")) + 1)
Also 2 lines.