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?)
Related
i need some help.
i need to get there text file value on Quot ("") on multi textbox1, textbox2, textbox3. but can only get on value (first value on textbox1)
now a time i just get one value (firt value on Quot)
text file (2.txt):
C:\contexture\img2itp.exe "\mynetwork\1.png" "\mynetwork\2.png" "148"
code vb:
Using sr As New StreamReader("C:\test\2.txt")
Dim line As String
' Read the stream to a string and write the string to the console.
line = sr.ReadToEnd()
Dim s As String = line
Dim i As Integer = s.IndexOf("""")
Dim f As String = s.Substring(i + 1, s.IndexOf("""", i + 1) - i - 1)
TextBox1.Text = f
thanks for a help :)
Regex Match
What Is Regex :
A regular expression is a pattern that the regular expression engine attempts to match in input text. A pattern consists of one or more character literals, operators, or constructs.
Source: https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx
Here we could consider two Regex Expressions to solve this problem a simple version and a more complex creating capture groups.
Simple one :
"(.*?)"
Here is the explanation: https://regex101.com/r/mzSmH5/1
Complex One :
(["'])(?:(?=(\\?))\2.)*?\1"(.*?)"
Here is an explanation: https://regex101.com/r/7ZMVsB/1
VB.NET Implementation
This would be a job for a Regex.Matches which would work like this:
Dim value As String = IO.File.ReadAllText("C:\test\2.txt")
Dim matches As MatchCollection = Regex.Matches(value, """(.*?)""")
' Loop over matches.
For Each m As Match In matches
' Loop over captures.
For Each c As Capture In m.Captures
' Display.
Console.WriteLine("Index={0}, Value={1}", c.Index, c.Value)
Next
Next
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)
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.
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
i just wanna ask:
i have a label40.text
with a content of {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}
and i also have have a label39.text that will change its output everytime a certain changes happens.
My question is
How can i embed this simulation through a code?
If Label39.text = "a" then the content of label40.text "a" will be remove and the list of alphabets will be remain alphabetically.
I want that also to be happen anytime my label39.text will change its value "RANDOMLY"
Example if label39.text = "a,b,c,d,x,z" then
label40.text = "e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y"
this is my code so far
Dim patterns As String
patterns = Label39.Text
Dim tobefollow As String
tobefollow = Label40.Text
Dim matches As MatchCollection = Regex.Matches(patterns, tobefollow)
If Regex.IsMatch(patterns, tobefollow) Then
'this where i will put my code to make my example
End If
First of all, note that you are populating the patterns and tobefollow variables wrongly (you were doing it right in the other question); it should be:
patterns = Label40.Text
tobefollow = Label39.Text
Also bear in mind that what you want can easily be accomplished without relying on Regex; for example via:
If (Label40.Text.ToLower().Contains(Label39.Text.ToLower())) Then
'this where i will put my code to make my example
End If
Regarding what you want this time, you can rely on .Replace: .Replace("text to be deleted", "") will remove this letter; but you have also to account for the commas. Code to be put inside the condition:
Dim origString As String = Label40.Text
Label40.Text = Label40.Text.ToLower().Replace(Label39.Text.ToLower() & ",", "")
If (origString = Label40.Text) Then
'It means that it does not have any comma, that is, refers to the last letter
Label40.Text = Label40.Text.ToLower().Replace("," & Label39.Text.ToLower(), "")
End If
An alternate answer would to use the String.Split and the String.Join Methods to breakdown your strings into individual characters then remove them from the List and join them back together. Here is a Function that does that:
Private Function RemoveLetters(str1 As String, str2 As String) As String
Dim sep() As String = {","}
Dim list1 As List(Of String) = str1.Split(sep, StringSplitOptions.None).ToList
Dim list2 As List(Of String) = str2.Split(sep, StringSplitOptions.None).ToList
For Each s As String In list2
list1.Remove(s)
Next
Return String.Join(",", list1)
End Function
you would use it like this:
Label40.Text = RemoveLetters(Label40.Text, Label39.Text)