How to find a phrase in a string based on a character - vb.net

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

Related

Vb.net find and replace within paragraph

What would be the efficient way to read a paragraph, and replace anything between square brackets []? In my case following paragraph,
I agree to [Terms of Use|https://www.google.com/terms-use], [Privacy Statement|https://www.google.com/privacy-statement] and [Misc Term|https://www.google.com/misc-terms]
should parsed as,
I agree to Terms of Use, Privacy Statement and Misc Term
You can use the following regular expression pattern to match the brackets:
\[[^]]+]
This is what the pattern means:
\[ match an open bracket
[^]]+ match anything but a closed bracket one or more times
] match a closed bracket
Here is an example fiddle: https://regex101.com/r/Iyk9kR/1
Once you have the matches, you would:
Use Regex.Replace (documentation)
Use the MatchEvaluator overload
In the MatchEvaluator, use String.Split (documentation) on the pipe character
Dynamically build your anchor tag by setting the href attribute to the second match of the split and the innerHTML to the first match of the split
It might be worth adding some conditional checking in between steps 2 and 3, but I'm not sure of your exact requirements.
Here is an example:
Imports System
Imports System.Text.RegularExpressions
Public Module Module1
Public Sub Main()
Dim literal = "I agree to [Terms of Use|https://www.google.com/terms-use], [Privacy Statement|https://www.google.com/privacy-statement] and [Misc Term|https://www.google.com/misc-terms]"
Dim regexPattern = "\[[^]]+]"
Dim massagedLiteral = Regex.Replace(literal, regexPattern, AddressOf ConvertToAnchor)
Console.WriteLine(massagedLiteral)
End Sub
Private Function ConvertToAnchor(m As Match) As String
Dim matches = m.Value.Split("|"c)
Return "" & matches(0).Substring(1) & ""
End Function
End Module
Fiddle: https://dotnetfiddle.net/xUE8St
Dim rtnStr = "String goes here"
Dim pattern As String = "\[.*?\]"
If Regex.IsMatch(rtnStr, pattern) Then
Dim matches = Regex.Matches(rtnStr, pattern, RegexOptions.IgnoreCase)
For index As Integer = 0 To matches.Count - 1
If matches(index).ToString().Contains("|") Then
Dim splitBracket = matches(index).ToString().Split("|")
Dim linkName = String.Empty
Dim linkUrl = String.Empty
If splitBracket.Length > 0 Then
linkName = splitBracket(0).Replace("[", "")
linkUrl = splitBracket(1).Replace("]", "")
End If
Dim linkHtml = "<a class=""terms"" href=""javascript: void(0);"" data-url=" + linkUrl + ">" + linkName + "</a>"
rtnStr = rtnStr.Replace(matches(index).ToString(), linkHtml)
End If
Next
End If
#Html.Raw(rtnStr)

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

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

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.

VB.net - 'Property Chars: Is ReadOnly' error in replacing letter of a string

This private sub keeps telling me that 'Property Chars: Is ReadOnly'.
Where have I gone wrong? StrWord is a string, e.g. 'banana'.
What I was hoping it would do is loop through the word, and if the 'guess' (a single letter) matches any letter in the string (StrWord), it would replace it in the corresponding letter in the textbox of the word.
So hangman, more or less.
Thanks and regards,
Cameron.
Private Sub Lookup(ByVal Guess)
Dim Count As Integer = 0
For Each Character As Char In StrWord
If Character = Guess Then
txtResult.Text(Count) = Guess
Else
Count += 1
End If
Next
End Sub
Strings in .NET are immutable. That means you cannot change them. Instead, you need to create a new string and assign it to the Text property. You will find the System.Text.StringBuilder class to be helpful as well, as it is mutable, and you can convert it into a String with the the ToString method.
Try something like this:
Private Sub Lookup(ByVal Guess As Char)
Dim temp as new StringBuilder(txtResult.Text)
Dim Count As Integer = 0
For Each Character As Char In StrWord
If Character = Guess Then
temp.Chars(Count) = Character
Else
Count += 1
End If
Next
txtResult.Text = temp.ToString()
End Sub
or this:
Private Sub Lookup(ByVal Guess As Char)
Dim temp as new StringBuilder()
Dim Count As Integer = 0
For Each Character As Char In StrWord
If Character = Guess Then
temp.Append(Character)
Else
temp.Append("*")
Count += 1
End If
Next
txtResult.Text = temp.ToString()
End Sub
Do you have the textbox set to ReadOnly to keep the user from modifying it? If so, you may need to change it from ReadOnly to make your change, then change it back to ReadOnly.
You could also try changing it this way:
txtResult.Text.Replace(Character, Guess)