Editing a string in VB - vba

I need to get username from email address by removing the part after "#" symbol. For example,
Dim uemail As String
Dim uname As String
umail = email_tb.Text.ToString() 'Suppose this returns abc.xyz#pqr.com
uname = umail (and some code) 'This will return abc.xyz only

Using VB you can do this by using the Split method:
Dim umail = email_tb.Text.ToString()
Dim uname As String = Split(umail, "#")(0)
Using VB.NET you could use the Substring and the IndexOf methods to achieve this:
Dim umail = email_tb.Text.ToString()
Dim uname As String = umail.Substring(0, umail.IndexOf("#"))

One efficient way, use pure string methods like IndexOf, Substring or Remove:
Dim uname = mail.Remove(mail.IndexOf("#"c)) ' check if IndexOf returned -1 first
You could also split by this separator:
Dim tokens As String() = mail.Split("#"c)
Dim uname = tokens.First()

Related

Decode mail encoded-words =?utf-8?B?xxxx?=, =?utf-8?Q?xxxx?=

Is there a way to decode email subjects that are encoded? I know the dirty way of doing it is to get the string character between =?utf-8?B? xxx ?= and decoding that. But I have a program where I can get encoded strings like
=?utf-8?Bxxxx?= =?UTF-8?B?xxxx?= ...
Right now I'm doing something like this
If codedString.ToUpper().StartsWith("=?UTF-8?B?") Then
Dim temp As String = codedString.SubString(10)
Dim data = Convert.FromBase64String(temp)
Dim decodedString = ASCIIEncoding.ASCII.GetString(data)
'do something with decodedString
End If
But this doesn't work when the same string has multiple =?utf-8?B? encode like above. Also I can get strings with =?utf-8?Q encoding and =?windows-1252. Is there a way to tackle all of these encoding? I'm using Visual Studios 2017
I've never had trouble using this function to decode a email field value:
It finds matching utf-8 strings for types B or Q, and if type B, runs FromBase64String.
I'm sure you can manipulate for windows-1252.
Private Function DecodeEmailField(byVal strString as String) as String
DecodeEmailField = strString.toString()
Dim strMatch
Dim arrEncodeTypes = New String() {"B","Q"}
Dim strEncodeType as String
For Each strEncodeType in arrEncodeTypes
Dim objRegexB as RegEx = new RegEx("(?:\=\?utf\-8\?" & strEncodeType & "\?)(?:.+?)(?:\?=\s)", _
RegexOptions.Multiline or RegexOptions.IgnoreCase)
if (objRegexB.IsMatch(DecodeEmailField)) then
Dim thisMatch as Match = objRegexB.Match(DecodeEmailField)
For Each strMatch in thisMatch.Groups
Dim strMatchHold as String = strMatch.toString().Substring(("=?utf-8?" & strEncodeType & "?").length)
strMatchHold = strMatchHold.SubString(0,(strMatchHold.Length)-("?= ".Length))
If strEncodeType = "B" Then
Dim data() As Byte = System.Convert.FromBase64String(strMatchHold)
strMatchHold = System.Text.UTF8Encoding.UTF8.GetString(data)
End If
DecodeEmailField = Replace(DecodeEmailField,strMatch.toString(),strMatchHold)
Next
End If
Next
End Function

how to get the fix substring from dynamic string content?

I am developing VB.NET windows app. in VS 2010.
I want to get the substring
$CostCenterId|4^10
from the below string .
PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian
Rupee^$CostCenterId|4^10$LedgerId|2^3$
The position of current string ($CostCenterId|4^10) in the sequence may be change.
but it will always between the two $ sign.
I have written the below code, but confused abt what to write next ?
Public Sub GetSubstringData()
dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian
Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Dim CostIndex As Integer
CostIndex = sDiscription.IndexOf("CostCenterId")
sDiscription.Substring(CostIndex,
End Sub
Have a look into the Split function of a string. This allows you to split a string into substrings based on a specified delimiting character.
You can then do this:
Dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Debug.WriteLine("$" + sfullString.Split("$"c)(3))
Result: $CostCenterId|4^10
You will probably want to do some error checking to make sure the string actually contains the data you expect though.
However looking at the data, what you have is a string containing key-value pairs so you would be better to have a property to hold the CostCenterId and extract the data like this:
Public Property CostCenterId As String
Public Sub Decode(ByVal code As String)
For Each pair As String In code.Split("$"c)
If pair.Length > 0 AndAlso pair.Contains("|") Then
Dim key As String = pair.Split("|"c)(0)
Dim value As String = pair.Split("|"c)(1)
Select Case key
Case "CostCenterId"
Me.CostCenterId = value
End Select
End If
Next
End Sub
Then call it like this:
Decode("PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$")
Why not split() the string by $ into an array, and then look for the element which contains CostCenterId
This should work:
Dim token = "$CostCenterId"
Dim costIndexStart As Integer = sfullString.IndexOf(token)
Dim costIndexEnd As Integer = sfullString.IndexOf("$", costIndexStart + token.Length)
Dim cost As String = sfullString.Substring(costIndexStart, costIndexEnd - costIndexStart + 1)
Result: "$CostCenterId|4^10$"
If you want to omit the dollar-signs:
Substring(costIndexStart + 1, costIndexEnd - costIndexStart - 1)
Try something like this:
Dim CostIndex As Integer
CostIndex = sDiscription.IndexOf("CostCenterId")
auxNum = sDiscription.IndexOf("$"c, CostIndex) - CostIndex
sResult = sDiscription.SubString(CostIndex, auxNum)
Your string,
Dim xString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Substring process,
xString = xString.Substring(xString.IndexOf("$CostCenter"), xString.IndexOf("$", xString.IndexOf("$CostCenter") + 1) - xString.IndexOf("$CostCenter"))
Try this Code:
Dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian" _
& "Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Dim sp() As String = {"$"}
Dim ar() As String = sfullString.Split(sp, StringSplitOptions.RemoveEmptyEntries)
Array.Sort(ar)
MsgBox("$" & ar(0))

How i can get selected parts from string?

How i get string like
'EJ0004','EK0001','EA0001'
from string like
{Emaster.Emp_Code}='EJ0004' OR {Emaster.Emp_Code}='EK0001' OR {Emaster.Emp_Code}='EA0001'
in VB.NET?
You can use a regular expression.
Example:
Sub Main
Dim s = "{Emaster.Emp_Code}='EJ0004' OR {Emaster.Emp_Code}='EK0001' OR {Emaster.Emp_Code}='EA0001'"
Dim pattern = "('\w*')"
Dim matches = Regex.Matches(s, pattern)
Dim values = matches.OfType(Of Match).Select(Function(m) m.Value)
For Each v in values
Console.WriteLine(v)
Next
Console.WriteLine(String.Join(",", values))
End Sub
Output:
'EJ0004'
'EK0001'
'EA0001'
'EJ0004','EK0001','EA0001'
there are many ways you could do this, here i offer one simple way:
dim yourString as string = 'This is the variable which holds your initial string
dim newString as string = yourString.replace("{Emaster.Emp_Code}=", "").replace(" OR ",",")
Now newString will hold 'EA0001' Or whatever.
If you want it without the '' then do
dim newString as string = yourString.replace("{Emaster.Emp_Code}=", "").replace("'","").replace(" OR ",",")

Flip letters of a string - Visual Basic

Simple coding assignment: Take text from a textbox and flip it so it's backwords:
i.e. Hello My Name Is David would be "divad si eman ym olleh" ( The program doesn't have to match case, just the letters)
This is something I found, do you have any other methods?
Dim str As String = Textbox1.Text
Dim arr As New List(Of Char)
arr.AddRange(str.ToCharArray)
arr.Reverse()
For Each l As Char In arr
lblOne.Text &= l
Next
You can do it in one line with using the StrReverse function (in Microsoft.VisualBasic).
Dim myText As String = "My Name is Dave"
Dim revText As String = StrReverse(myText)
Quick one liner.
lblOne.Text = String.Join("", "divad si eman ym olleh".Reverse())
Microsoft.VisualBasic
Dim myText As String = My Name is abc
Dim revText As String = StrReverse(myText)
Output: "cba si eman ym"
You can use String.Join instead of looping through each character and concatenating:
lblOne.Text = String.Join("", arr)
create a function that accepts string an returns a reversed string.
Function Reverse(ByVal value As String) As String
Dim arr() As Char = value.ToCharArray()
Array.Reverse(arr)
Return New String(arr)
End Function
and try using it like this,
lblOne.Text = Reverse(Textbox1.Text)
Here is a similar way but with fewer number of lines.
Dim Original_Text As String = "Hello My Name is Ahmad"
Dim Reversed_Text As String = ""
For i = Original_Text.Length To 1 Step -1
Reversed_Text &= Original_Text.Substring(i, 1)
Next
The simplest method to reverse a string is :
Dim s As String = "1234ab cdefgh"
MessageBox.Show(s.AsEnumerable.Reverse.ToArray)
First Create a textbox, it will be TextBox1
then create a button and name it Reverse
then Create a label, it will be Label1
Now double click on Reverse Button (Go to Button Click Event)
and type following code.
and run software And type your string in textbox and click on reverse button.
Dim MainText As String = TextBox1.Text
Dim revText As String = StrReverse(MainText)
Label1.Text = revText

Split a String into 2 Variables

What I'm trying to do here is Capture 2 Variables from a Textbox
Here is an example of whats going to be in here.
User:Pass
I want to declare everything before the : as user and everything after the : as pass.
I've Googled, and found a few things, but I couldn't seem to get it working fully.
Dim words As String() = textbox1.text.Split(":")
Dim user as String = words(0)
Dim pass as String = words(1)
Dim str = "User:Pass"
Dim split = str.Split(":")
Dim user as String
Dim password as String
If (split.Count = 2) then
user=split(0).ToString()
password = split(1).ToString()
End If
Split on the :, if there are 2 entries in the resulting array, populate the user variable with the first item, and the password variable with the second.
Have a look at the split function.
http://msdn.microsoft.com/en-us/library/6x627e5f%28v=vs.80%29.aspx
Dim user As String
Dim pass As String
Dim iPosEQ As Integer
iPosEQ = textbox1.text.IndexOf(":", System.StringComparison.Ordinal)
kv(0) = textbox1.text.Substring(0, iPosEQ - 1)
kv(1) = textbox1.text.Substring(iPosEQ + 1)
This works even with passwords (or users) with ":"