How i can get selected parts from string? - vb.net

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 ",",")

Related

VB.net need help parsing a substring

I have a value I am capturing from an Http Request
Dim someValue As String = Request.Params("search")
Here is the value of my string:
?MyId1=VALUE1&MyId2=VALUE2&MyBoolen=True
I am trying to capture VALUE2. I tried the below code, but haven't had any success.
If Not String.IsNullOrEmpty(someValue) Then
Dim x = someValue.Substring(someValue.IndexOf("&"c) + 1)
If Not String.IsNullOrEmpty(someValue) Then
Dim y = x.Substring(someValue.IndexOf("="c) + 1)
End If
End If
How can I do this?
It looks like you're overthinking this. The Request object will let you look up the MyId2 value directly:
Dim MyId2 As String = Request.QueryString("MyId2")
It's also possible this is a nested query string, where what you actually have is something more like this:
/?search=%3FMyId1%3DVALUE1%26MyId2%3DVALUE2%26MyBoolen%3DTrue
This would give you the original string after the runtime URL Decodes the search element. In that case, you should look at the HttpUtility.ParseQueryString() method, rather than trying to do this yourself:
Dim search As String = Request.Params("search")
Dim searchValues As NameValueCollection = HttpUtility.ParseQueryString(search)
Dim MyId2 As String = searchValues("MyId2")
Which could even be written as a one-liner if we really wanted:
Dim MyId2 As String = HttpUtility.ParseQueryString(Request.Params("search"))("MyId2")
But if you really wanted to parse this by hand, one of the nice things about this is everything should be URL-encoded. This means you don't have worry about stray & or = characters as part of the data, and a simple Split() call should be safe:
Dim MyId2 As String = ""
Dim items = someValue.Substring(1).Split("&"c)
For Each item As String In Items
Dim parts = item.Split("="c)
If parts(0) = "MyId2" Then
MyId2 = parts(1)
Exit For
End If
Next
Or
Dim parts() As String = someValue.Substring(1).Split("&"c).
Select(Function(s) s.Split("="c)).
FirstOrDefault(Function(p) p(0) = "MyId2")
Dim MyId2 As String = If(parts IsNot Nothing, parts(1), "")

VB.net Trying to get text between first and second slashs only

I am trying to retrive the value of the text between the first and second backslashes... but my coding skills have brought me this far and no futher.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim TEST As String = "ONE\TWO\TRHREE\FOR\FIVE"
Dim splitted = TEST.Split("\"c)
Dim values = splitted.Skip(1).Take(splitted.Length - 2).ToArray()
MsgBox(values)
End Sub
Use regular expressions
Dim TEST as String = "ONE\TWO\TRHREE\FOR\FIVE"
Dim matches As MatchCollection = Regex.Matches(TEST, "\\(.|\n)*?\\", RegexOptions.IgnoreCase)
Now if you want those values to come out in message boxes
For Each ma As Match In matches
MsgBox(ma.ToString.Trim({"\"c}))
Next
This will get you both "TWO" and "FOR". If you want just "TWO" then matches(0) is all you need.
Alternatively, if you just want to get the matches into an array in one line, then have each value of the array in a single message box:
Dim values = Regex.Matches(TEST, "\\(.|\n)*?\\").Cast(Of Match)().[Select](Function(m) m.Value).ToArray()
MsgBox(String.Join(", ", values))
Use the Split function. It will split on a string and store the separated values in an array. This is the easiest of all the answers here and is probably the most correct way of doing this.
This is the VB way of doing it:
Dim s() As String = Split("ONE\TWO\TRHREE\FOR\FIVE", "\")
MessageBox.Show(s(1))
And this is the .NET way of doing it:
Dim mainString As String = "ONE\TWO\TRHREE\FOR\FIVE"
Dim s() As String = mainString.Split("\")
MessageBox.Show(s(1))
If you want "Two" as result, this should be the simplest approach:
Dim allToken As String() = "ONE\TWO\TRHREE\FOR\FIVE".Split("\"c)
Dim relevantPart = allToken.Skip(1).Take(1)
Dim result As String = String.Concat(relevantPart) ' "Two"
If you don't want a single string but a String() use ToArray:
Dim result As String() = relevantPart.ToArray()
Side-Note: you can't output an array directly, you could use String.Join:
MsgBox(String.Join(", ", result)) ' f.e. comma separated

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))

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

Left of a character in a string in vb.net

say if I have a string 010451-09F2
How to I get left of - from the above string in vb.net
I want 010451
The left function doesn't allow me to specify seperator character.
Thanks
Given:
Dim strOrig = "010451-09F2"
You can do any of the following:
Dim leftString = strOrig.Substring(0, strOrig.IndexOf("-"))
Or:
Dim leftString = strOrig.Split("-"c)(0) ' Take the first index in the array
Or:
Dim leftString = Left(strOrig, InStr(strOrig, "-"))
' Could also be: Mid(strOrig, 0, InStr(strOrig, "-"))
Dim str As String = "010451-09F2"
Dim leftPart As String = str.Split("-")(0)
Split gives you the left and right parts in a string array. Accessing the first element (index 0) gives you the left part.
Sorry not sure on the vb syntax, but the c# is
string mystring ="010451-09F2";
string whatIwant = mystring.Split('-')[0];
Get the location of the dash first (or do it inline), and use that value for the left. This is old school VBA, but it'll be something like this:
Left(YourStringWithTheDash, InStr(YourStringWithTheDash)-1)
dim s as String = "010451-09F2"
Console.WriteLine(s.Substring(0, s.IndexOf("-")))
Console.WriteLine(s.Split("-")(0))
Use something like this:
Mid("010451-09F2",1,InStr("-"))
Dim sValue As String = "010451-09F2"
Debug.WriteLine(sValue.Substring(0, sValue.IndexOf("-"c)))
This helped
Dim str1 as string = me#test.com
Dim str As String
str = Strings.Left(str1, str1.LastIndexOf("#"))