how to select the strings between the textbox.contain() code? - vb.net

What I want to do actually is I want to find a strings in a textbox. My idea is using IF to find the current string for example;
If Textbox1.Contain("<") AndAlso Textbox1.Contain(">") Then
'I want to select the strings between the < and > to do MySQL command.
End If
How can I do that? Thank you guys for your help!

A solution without messing with RegEx could be this (it really depends on your needs):
<HideModuleName>
Public Module StringExtensions
<Extension>
Public Function GetFirstStringBetween(ByVal sender As String,
ByVal delimiterA As String,
ByVal delimiterB As String) As String
If sender.Contains(delimiterA) AndAlso sender.Contains(delimiterB) Then
Dim rightPart As String = sender.Substring(sender.IndexOf(delimiterA) + 1)
If rightPart.Contains(delimiterB) Then
Return rightPart.Substring(0, sender.IndexOf(delimiterB) - 1)
End If
End If
Return sender
End Function
End Module
Usage:
Dim str As String = "<Hello World> <Bye World>"
Dim result As String = str.GetFirstStringBetween("<", ">")
Console.WriteLine(result)

I'm not familiar with VB. But may be you want to try using regular expression. It's pretty useful for searching and extracting.
Something like below should work.
Dim strBetween As String
strBetween = Regex.Match(TextBox1.text, "<(.*?)>").Value
Or you can do as below example:
Sub Main()
Dim regex As Regex = New Regex("<(.*?)>")
Dim match As Match = regex.Match(TextBox1.text)
If match.Success Then
Console.WriteLine(match.Value)
End If
End Sub
Please let me know if it work.

Related

Get a specific value from the line in brackets (Visual Studio 2019)

I would like to ask for your help regarding my problem. I want to create a module for my program where it would read .txt file, find a specific value and insert it to the text box.
As an example I have a text file called system.txt which contains single line text. The text is something like this:
[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]
What i want to do is to get only the last name value "xxx_xxx" which every time can be different and insert it to my form's text box
Im totally new in programming, was looking for the other examples but couldnt find anything what would fit exactly to my situation.
Here is what i could write so far but i dont have any idea if there is any logic in my code:
Dim field As New List(Of String)
Private Sub readcrnFile()
For Each line In File.ReadAllLines(C:\test\test_1\db\update\network\system.txt)
For i = 1 To 3
If line.Contains("Last Name=" & i) Then
field.Add(line.Substring(line.IndexOf("=") + 2))
End If
Next
Next
End Sub
Im
You can get this down to a function with a single line of code:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Return File.ReadLines(fileName).Where(Function(line) RegEx.IsMatch(line, "[[[]Last Name=(?<LastName>[^]]+)]").Select(Function(line) RegEx.Match(line, exp).Groups("LastName").Value)
End Function
But for readability/maintainability and to avoid repeating the expression evaluation on each line I'd spread it out a bit:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Dim exp As New RegEx("[[[]Last Name=(?<LastName>[^]]+)]")
Return File.ReadLines(fileName).
Select(Function(line) exp.Match(line)).
Where(Function(m) m.Success).
Select(Function(m) m.Groups("LastName").Value)
End Function
See a simple example of the expression here:
https://dotnetfiddle.net/gJf3su
Dim strval As String = " [Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim strline() As String = strval.Split(New String() {"[", "]"}, StringSplitOptions.RemoveEmptyEntries) _
.Where(Function(s) Not String.IsNullOrWhiteSpace(s)) _
.ToArray()
Dim lastnameArray() = strline(1).Split("=")
Dim lastname = lastnameArray(1).ToString()
Using your sample data...
I read the file and trim off the first and last bracket symbol. The small c following the the 2 strings tell the compiler that this is a Char. The braces enclosed an array of Char which is what the Trim method expects.
Next we split the file text into an array of strings with the .Split method. We need to use the overload that accepts a String. Although the docs show Split(String, StringSplitOptions), I could only get it to work with a string array with a single element. Split(String(), StringSplitOptions)
Then I looped through the string array called splits, checking for and element that starts with "Last Name=". As soon as we find it we return a substring that starts at position 10 (starts at zero).
If no match is found, an empty string is returned.
Private Function readcrnFile() As String
Dim LineInput = File.ReadAllText("system.txt").Trim({"["c, "]"c})
Dim splits = LineInput.Split({"]["}, StringSplitOptions.None)
For Each s In splits
If s.StartsWith("Last Name=") Then
Return s.Substring(10)
End If
Next
Return ""
End Function
Usage...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = readcrnFile()
End Sub
You can easily split that line in an array of strings using as separators the [ and ] brackets and removing any empty string from the result.
Dim input As String = "[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim parts = input.Split(New Char() {"["c, "]"c}, StringSplitOptions.RemoveEmptyEntries)
At this point you have an array of strings and you can loop over it to find the entry that starts with the last name key, when you find it you can split at the = character and get the second element of the array
For Each p As String In parts
If p.StartsWith("Last Name") Then
Dim data = p.Split("="c)
field.Add(data(1))
Exit For
End If
Next
Of course, if you are sure that the second entry in each line is the Last Name entry then you can remove the loop and go directly for the entry
Dim data = parts(1).Split("="c)
A more sophisticated way to remove the for each loop with a single line is using some of the IEnumerable extensions available in the Linq namespace.
So, for example, the loop above could be replaced with
field.Add((parts.FirstOrDefault(Function(x) x.StartsWith("Last Name"))).Split("="c)(1))
As you can see, it is a lot more obscure and probably not a good way to do it anyway because there is no check on the eventuality that if the Last Name key is missing in the input string
You should first know the difference between ReadAllLines() and ReadLines().
Then, here's an example using only two simple string manipulation functions, String.IndexOf() and String.Substring():
Sub Main(args As String())
Dim entryMarker As String = "[Last Name="
Dim closingMarker As String = "]"
Dim FileName As String = "C:\test\test_1\db\update\network\system.txt"
Dim value As String = readcrnFile(entryMarker, closingMarker, FileName)
If Not IsNothing(value) Then
Console.WriteLine("value = " & value)
Else
Console.WriteLine("Entry not found")
End If
Console.Write("Press Enter to Quit...")
Console.ReadKey()
End Sub
Private Function readcrnFile(ByVal entry As String, ByVal closingMarker As String, ByVal fileName As String) As String
Dim entryIndex As Integer
Dim closingIndex As Integer
For Each line In File.ReadLines(fileName)
entryIndex = line.IndexOf(entry) ' see if the marker is in our line
If entryIndex <> -1 Then
closingIndex = line.IndexOf(closingMarker, entryIndex + entry.Length) ' find first "]" AFTER our entry marker
If closingIndex <> -1 Then
' calculate the starting position and length of the value after the entry marker
Dim startAt As Integer = entryIndex + entry.Length
Dim length As Integer = closingIndex - startAt
Return line.Substring(startAt, length)
End If
End If
Next
Return Nothing
End Function

Replacing character in a text file with comma delimited

I have a comma delimited file with sample values :
1,1076103,22-NOV-16,21051169,50,1083,AAA,TEXT
Question : how to replace the comma in the last column which is "AAA,TEXT"
The result should be this way:
1,1076103,22-NOV-16,21051169,50,1083,AAATEXT
There is an overload of String.Split which takes an argument telling it the maximum number of parts to return. You could use it like this:
Option Infer On
Option Strict On
Module Module1
'TODO: think up a good name for this function
Function X(s As String) As String
Dim nReturnParts = 7
Dim parts = s.Split({","c}, nReturnParts)
If parts.Count < nReturnParts Then
Throw New ArgumentException($"Not enough parts - needs {nReturnParts}.")
End If
parts(nReturnParts - 1) = parts(nReturnParts - 1).Replace(",", "")
Return String.Join(",", parts)
End Function
Sub Main()
Dim s() = {"1,1076103,22-NOV-16,21051169,50,1083,AAA,TEXT",
"1,1076103,22-NOV-16,21051169,50,1083,BBBTEXT",
"1,1076103,22-NOV-16,21051169,50,1083,C,C,C,TEXT"}
For Each a In s
Console.WriteLine(X(a))
Next
Console.ReadLine()
End Sub
End Module
Outputs:
1,1076103,22-NOV-16,21051169,50,1083,AAATEXT
1,1076103,22-NOV-16,21051169,50,1083,BBBTEXT
1,1076103,22-NOV-16,21051169,50,1083,CCCTEXT
Is simple, but learn a bit how to use string ;)
Public Function MDP(strWork As String)
Dim splitted() As String = strWork.Split(","c)
Dim firsts As New List(Of String)
For i As Integer = 0 To splitted.Count - 3
firsts.Add(splitted(i))
Next
Dim result As String = System.String.Join(",", firsts)
Return result & "," & splitted(splitted.Count - 2) & splitted(splitted.Count - 1)
End Function
Then call with:
Dim finished As String = MDP("1,1076103,22-NOV-16,21051169,50,1083,AAA,TEXT")

Can you get a list of parameters in VB.net Compact Framework?

In VB.Net Compact Framework 3.5 is it possible to get a list of the Parameters that are passed to a method?
For example,
Private Sub TestSub(Param1 as String, Param2 as Integer, Param3 as List(Of String)
'Get List of Parameters
End Sub
Is it possible to get the names of the parameters and what they are populated with at the point it says 'Get List of Parameters
Any help would be much appreciated.
Thanks
Take a look at https://msdn.microsoft.com/pt-br/library/system.reflection.methodbase.getcurrentmethod(v=vs.110).aspx
and https://msdn.microsoft.com/pt-br/library/system.reflection.methodbase.getparameters(v=vs.110).aspx for further information.
But I'm assuming that you're looking for something like this:
Private Function GetParameters(ByVal info As MethodBase) As String
Dim lst = info.GetParameters()
Dim strParameters As String = ""
For Each item In lst
If strParameters <> "" Then strParameters += ","
strParameters += item.Name
Next
Return strParameters
End Function
And to invoke:
Private Sub TestSub(ByRef a As String, ByRef b as String)
Dim strParameters As String = GetParameters(System.Reflection.MethodBase.GetCurrentMethod())
End Sub
The return should be "a,b".
Best regards.

How to find a phrase in a string based on a character

Let's say I have the following string:
sdfhahsdfu^asdhfhasdf^asd7f8asdfh^asdfhasdf^testemail#email.com^asdhfausdf^asodfuasdufh^alsdfhasdh
What's the best way of extracting the email from that string? I thought of maybe split(string, "#") but then I'm not sure where to go from there.
Note: the email will always be flanked by ^ on either side, but the position in the string will be different depending on the string.
You can use Regex to find your string. Try something like:
System.Text.RegularExpressions.Regex.Match("\^[^\^]+#[^\^]+\^", myString)
I would split over ^ and then loop through all items to find something containing a #
'1 form with:
' 1 command button: name=Command1
Option Explicit
Private Sub Command1_Click()
Dim lngItem As Long
Dim strString As String
Dim strItem() As String
strString = "sdfhahsdfu^asdhfhasdf^asd7f8asdfh^asdfhasdf^testemail#email.com^asdhfausdf^asodfuasdufh^alsdfhasdh"
strItem = Split(strString, "^")
For lngItem = 0 To UBound(strItem)
If InStr(strItem(lngItem), "#") > 0 Then
DoEmail strItem(lngItem)
End If
Next lngItem
End Sub
Private Sub DoEmail(strEmail As String)
Print strEmail
End Sub

String Manipulation with no delimiter

I have a string where I need to replace every character in that string with another value. That string has no delimiter. Is it possible to step through that string and replace every value with a set of predetermined values? I would like to keep it to one function as it is going to live within SSRS
Dim stringToChange As String = "123456ALWRYA"
I would then have to step through the string and replace all off the current values with new ones.
i.e. A=001, B=002, 1=101, 2=102, etc.
Is this possible if the string does not have a delimiter?
Thanks in advance!
SSRS Custom code has a pretty limited dialect, but this worked for me.
Add the following to the report Custom Code:
Function SingleReplace (SingleChar As String) As String
Select Case SingleChar
Case "A"
SingleReplace = "001"
Case "B"
SingleReplace = "002"
Case Else
SingleReplace = SingleChar
End Select
End Function
Function CustomReplace (BaseString As String) As String
Dim NewString As New System.Text.StringBuilder
For Each SingleChar As Char in BaseString
NewString.Append(SingleReplace(SingleChar))
Next
Return NewString.ToString()
End Function
Call this in a report expression with:
=Code.CustomReplace(Fields!MyString.Value)
Works for me in a simple report/table:
This is basically what Styxxy suggested...with a Dictionary for the looking up the values:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim stringToChange As String = "123456ALWRYA"
Debug.Print(stringToChange)
Dim changedString = ConvertString(stringToChange)
Debug.Print(changedString)
End Sub
Private Function ConvertString(ByVal inStr As String) As String
Static dict As New Dictionary(Of Char, String)
If dict.Count = 0 Then
dict.Add("A"c, "001")
dict.Add("B"c, "002")
dict.Add("1"c, "101")
dict.Add("2"c, "102")
' ... etc ...
End If
Dim sb As New System.Text.StringBuilder
For Each c As Char In inStr.ToUpper
If dict.ContainsKey(c) Then
sb.Append(dict(c))
Else
' ... possibly throw an exception? ...
sb.Append(c)
End If
Next
Return sb.ToString
End Function