VB.NET - Replace string using or statement - vb.net

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)

Related

String.replace adding extra characters

I am trying to replace some words in mails in Outlook. Here is my code for it
Dim input As String = mail.HTMLBody
Dim pattern As String = "QWQ[a-z][a-z][0-9][0-9][0-9][0-9][0-9]"
Dim replacement As String
Dim rgx As New Regex(pattern)
Dim match As Match = Regex.Match(input, pattern)
While (match.Success)
replacement = "A" + match.Value + "A"
input = input.Replace(match.value, replacement)
match = match.NextMatch()
End While
mail.HTMLBody = input
For this input
QWQrt12345
QWQrt1234533
wwQWQrt12345
QWQrt1234534
qwwQWQrt12345
I expect output as
AQWQrt12345A
AQWQrt12345A33
wwAQWQrt12345A
AQWQrt12345A34
qwwAQWQrt12345A
But the output I am getting is
AAAAAQWQrt12345AAAAA
AAAAAQWQrt12345AAAAA33
wwAAAAAQWQrt12345AAAAA
AAAAAQWQrt12345AAAAA34
qwwAAAAAQWQrt12345AAAAA
What can be the issue?
The description of String.Replace states,
Returns a new string in which all occurrences of a specified string in
the current instance are replaced with another specified string.
The important takeaway there is, "all occurrences ... are replaced." Since your replacement string is also a match for your regular expression pattern, it will be replaced (thus adding another set of 'A') upon every iteration.
Try a test case using something like this, instead:
replacement = match.Value.Replace("Q", "A")
The details here don't matter (you can change whatever you want), the point is that you change something so that your strings aren't matched repeatedly.
simply put your adding 'A' + match + 'A' evertytime you match .
Resulting in the AAAAA before and after your input. I've been voted down?
ok I explain your first match input result is exactly what you have inputted(all characters could be matched), you then add "A" both sides and want to replace your replaced value with the original value.
Here's the c# code to get expected value :
var input = "QWQrt1234533"; //your second line example
const string pattern = "QWQ[a-z][a-z][0-9][0-9][0-9][0-9][0-9]";
var rgx = new Regex(pattern);
Match match = Regex.Match(input, pattern);
while (match.Success)
{
var replacement= "A" + match.Value + "A";
input = input.Replace(match.Value, replacement);
match = match.NextMatch();
}
Console.Write(input);
resulting in your exected : "AQWQrt12345A33"
not getting your results even with the posted VB code (you did not edit the original after my first response?)

How to get the first value in textbox

how can i get the first value in a text box and place it to a label. Example, I want to get the word "look" in the textbox that I input was "look like".
You could use substring, this will split the string or aka your textbox.
This takes two params, The starting index of the string and the 2nd param is the length. I have put str.indexof in the 2nd param to get the index of where the space is.
dim str as string
Label1.Text = str.Substring(0, str.IndexOf(" "))
This code is not tested, I only used visual basic for a little bit when i was 12.
you can simply split the value by " " space and take the first one from result array
if(!String.IsNullOrEmpty(textBox1.Text))
{
lable1.Text = textBox1.Text.Split(" ").first();
}
textboxValue = Textbox.Text;
str = textboxValue.Split(" ").first();

Lowercase the first word

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.

Remove the character alone from the string

My code retrieves the data from various resources .
And output will be like below
UNY4/4/2010
hds04/5/2010
saths04/22/2013
But I want the output like this
4/4/2010
4/5/2010
04/22/2013
Is there any way to do this ?
You need to use a regular expression that finds all uppercase and lowercase characters and replaces them with a blank, like this:
Dim rgx As New Regex("[a-zA-Z]")
str = rgx.Replace(str, String.Empty)
An alternate solution is to look for the first numeric digit, then discard all text before that.
Function GetDate(data As String) As Date
Dim indexFirstNum As Integer = data.IndexOfAny("0123456789".ToCharArray())
Dim datePortion As String = data.Substring(indexFirstNum)
Return Date.Parse(datePortion)
End Function

VB.NET Get text in between Quotations or other symbols

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.