I want to be able to extract a string in between quotation marks or parenthesis etc. to a variable. For example my text might be "Hello there "Bob" ". I want to extract the text "Bob" from in between the two quotation marks and put it in the string "name" for later use. The same would be for "Hello there (Bob)". How would I go about this? Thanks.
=======EDIT======
Sorry, I worded this poorly. Ok, so lets say I have a textbox(Textbox1) and a button. If the user inputs the text: MsgBox "THIS IS MY MESSAGE" I want that when the Button is pressed, only the text THIS IS MY MESSAGE is displayed.
This is a solution very simple:
Dim sAux() As String = TextBox1.Text.Split(""""c)
Dim sResult As String = ""
If sAux.Length = 3 Then
sResult = sAux(1)
Else
' Error or something (number of quotes <> 2)
End If
There are basically three methods -- regular expressions, string.indexof and substring and finally looping over the characters one by one. I would avoid the latter as it is just reinventing the wheel. Whether to use regexs or indexof depends upon the complexity of your requirements and data. Indexof is a bit wordy but fairly straightforward and possibly just what you want in this case.
Dim str as String = "Hello there ""Bob"""
Dim startName as Integer
Dim endName as Integer
Dim name as String = ""
startName = str.IndexOf("""")
endName = str.Indexof("""", If(startName > 0, startName,0))
If (endName>startName) Then
name = str.SubString(startName, endName)
End If
If you need to do this for arbitrary symbols, then you want regexs.
Related
I am having trouble, here is my code.
TextBox2.Text = TextBox1.Text.Replace("a" Or "A", "test")
Simply what I have failed to find a straight answer for. I want to find lowercase "a" and replace it with "test". If it finds a capital "A" I also want to replace it with "test". When I try and OR statement it throws an error. I am looking for a solution, thank you for your time.
You just can't apply and Or operator between two strings.
If you don't want to learn Regex you can concatenate infinite .replace() calls as the return value is a new string.
If you don't care of upper or lower and just want to replace the a character (eather upper and lower) you can use .toUpper() or .toLower() on the input string before passing it to .replace()
Test 1:
Dim input = "abcABC"
output = input.replace("a", "-").replace("A", "-")
Test 2:
Dim input = "abcABC"
output = input.toLower().replace("a", "-")
Test 1 will output this string: "-bc-BC"
Test 2 will output this string: "-bc-bc"
you can simply use a Regex like :
Dim rgx As New RegularExpressions.Regex("[aA]")
If rgx.IsMatch(TextBox1.Text) Then
TextBox2.Text = "test"
End If
OR use this if statement
If TextBox1.text.Contains("a") Or TextBox1.text.Contains("A") Then
TextBox2 = "test"
End If
Or just go to the official documentation of [string.replace] site
as TnTinMn suggested , same case can be found there
TextBox2.Text = TextBox1.Text.Replace("a", "test").Replace("A","test)
Let me say, I hate working with strings! I'm trying to find a way to split a string on brackets. For example, the string is:
Hello (this is) me!
And, from this string, get an array with Hello and me. I would like to do this with parentheses and braces (not with brackets). Please note that the string is variable, so something like SubString wouldn't work.
Thanks in advance,
FWhite
You can use regular expressions (Regex), below code should exclude text inside all parenthesis and braces, also removes an exclamation mark - feel free to expand CleanUp method to filter out other punctuation symbols:
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim re As New Regex("\(.*\)|{.*}") 'anything inside parenthesis OR braces
Dim input As String = "Hello (this is) me and {that is} him!"
Dim inputParsed As String = re.Replace(input, String.Empty)
Dim reSplit As New Regex("\b") 'split by word boundary
Dim output() As String = CleanUp(reSplit.Split(inputParsed))
'output = {"Hello", "me", "and", "him"}
End Sub
Private Function CleanUp(output As String()) As String()
Dim outputFiltered As New List(Of String)
For Each v As String In output
If String.IsNullOrWhiteSpace(v) Then Continue For 'remove spaces
If v = "!" Then Continue For 'remove punctuation, feel free to expand
outputFiltered.Add(v)
Next
Return outputFiltered.ToArray
End Function
End Module
To explain the regular expression I used (\(.*\)|{.*}):
\( is just a (, parenthesis is a special symbol in Regex, needs to be escaped with a \.
.* means anything, i.e. literally any combination of characters.
| is a logical OR, so the expression will match either left or ride side of it.
{ does not need escaping, so it just goes as is.
Overall, you can read this as Find anything inside parenthesis or braces, then the code says replace the findings with an empty string, i.e. remove all occurrences. One of the interesting concepts here is understanding greedy vs lazy matching. In this particular case greedy (default) works well, but it's good to know other options.
Useful resources for working with Regex:
http://regex101.com/ - Regex test/practice/sandbox.
http://www.regular-expressions.info/ - Theory and examples.
http://www.regular-expressions.info/wordboundaries.html - How word boundaries work.
Try this code:
Dim var As String = "Hello ( me!"
Dim arr() As String = var.Split("(")
MsgBox(arr(0)) 'Display Hello
MsgBox(arr(1)) 'Display me!
Something like this should work for you:
Dim x As String = "Hello (this is) me"
Dim firstString As String = x.Substring(0, x.IndexOf("("))
Dim secondString As String = x.Substring(x.IndexOf(")") + 1)
Dim finalString = firstString & secondString
x = "Hello (this is) me"
firstString = "Hello "
secondString = " me"
finalString = "Hello me"
Does anybody know how to lowercase the first word for each line in a textbox?
Not the first letter, the first word.
I tried like this but it doesn't work:
For Each iz As String In txtCode.Text.Substring(0, txtCode.Text.IndexOf(" "))
iz = LCase(iz)
Next
When you call Substring, it is making a copy of that portion of the string and returning it as a new string object. So, even if you were successfully changing the value of that returned sub-string, it still would not change the original string in the Text property.
However, strings in .NET are immutable reference-types, so when you set iz = ... all you are doing is re-assigning the iz variable to point to yet another new string object. When you set iz, you aren't even touching the value of that copied sub-string to which it previously pointed.
In order to change the value of the text box, you must actually assign a new string value to its Text property, like this:
txtCode.Text = "the new value"
Since that is the case, I would recommend building a new string, using a StringBuilder object, and then, once the modified string is complete, then set the text box's Text property to that new string, for instance:
Dim builder As New StringBuilder()
For Each line As String In txtCode.Text.Split({Environment.NewLine}, StringSplitOptions.None)
' Fix case and append line to builder
Next
txtCode.Text = builder.ToString()
The solutions here are interesting but they are ignoring a fundamental tool of .NET: regular expressions. The solution can be written in one expression:
Dim result = Regex.Replace(txtCode.Text, "^\w+",
Function (match) match.Value.ToLower(), RegexOptions.Multiline)
(This requires the import System.Text.RegularExpressions.)
This solution is likely more efficient than all the other solutions here (It’s definitely more efficient than most), and it’s less code, thus less chance of a bug and easier to understand and to maintain.
The problem with your code is that you are running the loop only on each character of the first word in the whole TextBox text.
This code is looping over each line and takes the first word:
For Each line As String In txtCode.Text.Split(Environment.NewLine)
line = line.Trim().ToLower()
If line.IndexOf(" ") > 0 Then
line = line.Substring(0, line.IndexOf(" ")).Trim()
End If
// do something with 'line' here
Next
Loop through each of the lines of the textbox, splitting all of the words in the line, making sure to .ToLower() the first word:
Dim strResults As String = String.Empty
For Each strLine As String In IO.File.ReadAllText("C:\Test\StackFlow.txt").Split(ControlChars.NewLine)
Dim lstWords As List(Of String) = strLine.Split(" ").ToList()
If Not lstWords Is Nothing Then
strResults += lstWords(0).ToLower()
If lstWords.Count > 1 Then
For intCursor As Integer = 1 To (lstWords.Count - 1)
strResults += " " & lstWords(intCursor)
Next
End If
End If
Next
I used your ideas guys and i made it up to it like this:
For Each line As String In txtCode.Text.Split(Environment.NewLine)
Dim abc() As String = line.Split(" ")
txtCode.Text = txtCode.Text.Replace(abc(0), LCase(abc(0)))
Next
It works like this. Thank you all.
The part of the program I'm trying to write is supposed to take the users input, which is their name, and in a listbox spit out their initials. I have so far:
Dim initials As String
Dim indexspace As Integer
initials = name.Substring(0, 1)
indexspace = name.IndexOf(" ")
lstInvoice.Items.Add(String.Format(strFormat, "Invoice ID", initials & space))
When I run the program, I can get the first initial to pop up, but I am not certain how to get the second to pop up.
Thank you very much for your assistance on this matter, it is much appreciated
Q: How do I find a space (" ") in a string with VB.Net?
A: String.IndexOf (" ");
Q: How do I find subsequent spaces in the string?
A: Extract the substring of everything to the right of the first space you found.
Then do an ".IndexOf (" ")" of that substring.
Until you get to the end of the string, or until you get bored :)
I apologize for not writing it in VB but I am more familiar with C#. There is no reason to look for the index of a space. Just split the string on the space and then pull the first letter of each of the results in the array. For simplicity, I made an assumption that it was only two words in the string but you could loop through the array of results to put out all the initials if they included a middle name:
string name = "Test User";
string[] nameParts = name.Split(' ');
string initials = nameParts[0].Substring(0, 1) + nameParts[1].Substring(0, 1);
VB Version:
Dim name As String = "Test User"
Dim nameParts As String() = name.Split(" ")
Dim initials As String = nameParts(0).Substring(0, 1) & nameParts(1).Substring(0, 1)
Again this is a very simplistic approach to what you are asking. As #paxdiablo pointed out in his comments there are variations of names that will not match this pattern but you know you're program.
Okay, so in a program I'm working on in VB.NET I'm trying to make it so I can take in a list of strings (each on a different line). For each line I want to take in the line, and break it up into three parts. The first part goes from the beginning of the string to the first colon in the string, the second part goes from the first colon to the at symbol, and the last part goes from the at symbol to the end of the string.
For example, I'd take in a line of the series of lines:
hello:world#yay
I'd want to break it into three separate strings of "hello", "world", and "yay".
How would I do such a thing in VB.NET?
You can accomplish this with a Split. For example purposes, I am re-splitting a string which I could have saved off, so I wouldn't have to Split it again. However, it's simpler to understand this way:
Dim s as String = "hello:world#yay" 'This can be a string from a loop.
Dim hello As String = s.Split(":")(0) 'Get everything before colon.
Dim world As String = s.Split(":")(1).Split("#")(0) 'Get everything after colon, and split the result again, grabbing everything before the amp.
Dim yay As String = s.Split(":")(1).Split("#")(1) 'Get everything after colon, and split the result again, grabbing everything after the amp.
If you're reading from a text file, e.g.
Dim objReader As New StreamReader("c:\test.txt")
Dim s As String = ""
Dim hello As String
Dim world As String
Dim yay As String
Do
s = objReader.ReadLine()
If Not s Is Nothing Then
hello = s.Split(":")(0)
world = s.Split(":")(1).Split("#")(0)
yay = s.Split(":")(1).Split("#")(1)
End If
Loop Until s Is Nothing
objReader.Close()
Use the split command
Start by splitting the string with the ":" and then split the second edit element with the "#"
Look at string.indexOf and take it from there