How can I get the nickname and message from raw IRC data in vb.net - vb.net

Well basically I've got a vb.net script connecting to IRC, and I'm working on making it a basic chat system, but I've run into a problem.
Say I receive this:
:nickname!name#tw-32151D9B.hsd1.vt.comcast.net PRIVMSG #channel :message
I want to grab specific information to output to the user.
I want to grab nickname and message
How can I go about doing this?
I thought about using regex, but I can't figure out how to make regex grab message since there's nothing after it.

I love IRC. The following code will do what you want assuming your raw data is in the variable strData.
Dim strNickName As String = String.Empty
Dim strMessage As String = String.Empty
Dim intToMessage As Integer = 0
Dim intParse As Integer = 0
intParse = InStr(strData, "!")
strNickName = Mid(strData, 2, (intStart - 2))
intToMessage = InStr(strData, "PRIVMSG #")
intParse = InStr(Mid(strData, intToMessage, (Len(strData) - intToMessage)), ":")
strMessage = Mid(strData, (intToMessage + intStart), (Len(strData) - (intToMessage + intStart - 1)))

You can use RegEx to get everything between the first : and !
(?<=:).*?(?=!)
and then look for everything between the last #channel : and the end of the line
(?<=#channel :).*?(?=$)
This is simple but should take into account that someone may use a semi-colon (:) in the message.

Related

Cut String inside Quotation Mark

I have this String:
"[" & vbCrLf & " ""APPLE""" & vbCrLf & "]"
The only thing I need is APPLE.
I tried a few options with Split, Trim, Left and more, but they didn't work very well.
Thank you very much!
As the comments above have said, there's not enough information to give an answer without making assumptions, which could be wrong. I've assumed you want to extract the value between two quotation marks, regardless of what else is before or after.
If that's what you want, try this:
Dim Result As String = Nothing
Dim source As String = $"[{vbCrLf}""Apple""{vbCrLf}]"
Dim FirstQuote As Integer = source.IndexOf("""")
If FirstQuote > -1 And source.Length > FirstQuote Then
Dim SecondQuote As Integer = source.IndexOf("""", FirstQuote + 1)
If SecondQuote > FirstQuote Then
Result = source.Substring(FirstQuote + 1, SecondQuote - FirstQuote - 1)
End If
End If
If Result Is Nothing Then
'Handle Invalid Format
Else
'Process Result
End If
You would need to modify that so that you passed your source string, rather than defining it in the code. If you wanted to extract multiple words from a single string in the same format, just set FirstQuote = SecondQuote + 1, check that doesn't exceed the length of the source string and loop through again.
I am going to assume that you probably just need to get the first occurance of a string (in this case "apple") within square-brackets using split and so:
Dim AppleString As String = "This is an [Apple] or etc [...]"
console.WriteLine(AppleString.split("[")(1).split("]")(0).trim())
⚠️ This is not a solution for all purposes !!!

VB.NET - Get second hyperlink from string and set as LinkLabel text property

I have a tool that takes in an email and sorts the data into the appropriate fields. In the email, there are normally two hyperlinks that launch the ticket editor in IBM notes. One is a local link and one is a server link. The following code is able to get the local link as it is the first hyperlink that contains 'notes://' but I need to get the one for the server as well, which also starts with 'notes://".
For i = 0 To lines.Count + 1
If lines(i).StartsWith("notes://") Then
StartLine = i
Exit For
End If
Next
link_OpenRequestUsingNotes.Text = lines(StartLine)
I thought of writing some code to check the line about it to see if it matches a specific string, maybe with Regex?
For the local link it needs to look for:
"using a Notes client (local replica)"
For the server link it needs to look for:
"using a Notes client (Server):"
The hyperlink is below this text so it would need to look for those and then get the text on the next line.
These links are then set as the text for two link labels that the users can press and go to that link.
If someone could please help me find a way to get the server link, it would be greatly appreciated.
You can use this code:
link_OpenRequestUsingNotes_Local.Text = "" 'fields for local link
link_OpenRequestUsingNotes_Server.Text = "" 'field for server link
For i = 0 To lines.Count - 1
If lines(i).StartsWith("using a Notes client (local replica)") Then
link_OpenRequestUsingNotes_Local.Text = lines(i + 1)
ElseIf lines(i).StartsWith("using a Notes client (Server)")
link_OpenRequestUsingNotes_Server.Text = lines(i + 1)
End If
If link_OpenRequestUsingNotes_Local.Text <> "" AndAlso link_OpenRequestUsingNotes_Server.Text <> "" Then
Exit For
End If
Next i
You could use code like this to find the first two links:
Dim notes = Function(x) x.StartsWith("notes://")
Dim index As Integer = lines.FindIndex(notes)
If index <> -1 AndAlso index < (lines.Count - 1) Then
Dim firstLink As String = lines(index + 1)
' ... do something with "firstLink"...
Debug.Print(firstLink)
index = lines.FindIndex(index + 2, notes)
If index <> -1 AndAlso index < (lines.Count - 1) Then
Dim secondLink As String = lines(index + 1)
' ... do something with "secondLink"...
Debug.Print(secondLink)
End If
End If
I managed to fix it myself
Just add 1 to i (StartLine = i + 1) to go to the line below!
'Notes Server Link
For i = 0 To lines.Count - 1
If lines(i).StartsWith("Click here to open the request using a Notes client (Server):") Then
StartLine = i + 1
Exit For
End If
Next
link_OpenServerLink.Text = lines(StartLine)

Multiple string replace at one time

I have this string abcd, and I want to replace the a with [a|b] and the b with [c|d]
I try many ways to do it, like
Dim varString As String = "abcd"
varString = varString.Replace("a", "[a|b]")
varString = varString.Replace("b", "[c|d]")
The result I get is
[a|[c|d]][c|d]cd
Instead I want it like this
[a|b][c|d]cd
The problem is every time I use the replace function it backs to change the values I already replaced before so I replaced a with [a|b] but then when I do my second command to replace the b it changes the b in [a|b] that I just changed and I don't want this.
I tried to use StringBuilder but it gives the same result.
Please advise me,
I solved the problem by making an array in this way
Dim NewCommand As String = "abcd"
For i = 0 To LikeCommand.Length - 1
If LikeCommand(i) = "a" Then
NewCommand += "[a|b]"
ElseIf LikeCommand(i) = "b" Then
NewCommand += "[c|d]"
Else
NewCommand += LikeCommand(i)
End If
Next
LikeCommand = NewCommand
Or just switch the logic up. But obviously I'm thinking you're using a basic example for a more complex question.
dim varString as string = "abcd"
varString = varString.Replace("b" ,"[c|d]")
varString = varString.Replace("a" ,"[a|b]")
That would get you the desired results.

Searching text file and showing part of the text in a text box

I am working on a VB.net application where I have a very large text file. It is basically a large database of error codes with descriptions of how to clear the code after it. What I would like to do, is on the click of a button, search the text file for the specific code and display all text for just that error code into a text box. I have tried many different ways, but am unable to get it to work properly. I went through the entire text file and added a "|" to the beginning of each fault code so that I could specify where the code starts at.
Here is an example of a couple fault codes:
|ACAL-000 Fail to run DETECT Motn Cause: The AccuCal2 Motion failed to
nm. The AccuCal2 motion cannot be started. Remedy: Clear all the
errors before executing AccuCal2. |ACAL-001 Robot is not ready.
Cause: The robot is not ready. The system cannot issue motion
because it is in an error state. Remedy: Clear all faults, then retry
the operation.
If I search for "ACAL-000", I want it to show everything from the | before ACAL-000 to the bar before ACAL-001.
I would post the code that I have written, but I have tried so many different versions that I don't really know which one to post.
Any help you can provide would be greatly appreciated.
EDIT
Here is my current code after some editing and implementation of what has been recommended. Please see the comments below for more information on how I got to this point. A quick note, I am currently just using "|ACAL-000" for a test search. When this is complete, I have some other (already working) code that will put together a code from a couple of drop down lists.
Function ReadEmbeddedTextFileResource(embeddedResourceName As String) As String
Using stream As Stream = Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedResourceName)
If stream Is Nothing Then
Throw New FileNotFoundException("The resource '" & embeddedResourceName & "' was not found.")
End If
Using reader As StreamReader = New StreamReader(stream, True)
Return reader.ReadToEnd()
End Using
End Using
End Function
Function FindTextBetweenBars(bodyOfTextToSearch As String, textToLookFor As String) As String
Dim i As Integer = bodyOfTextToSearch.IndexOf(textToLookFor)
If i < 0 Then Return Nothing
Dim j As Integer = bodyOfTextToSearch.LastIndexOf("|", i)
If j < 0 Then j = 0
Dim k As Integer = bodyOfTextToSearch.IndexOf("|", i + Len(textToLookFor))
If k < 0 Then k = Len(bodyOfTextToSearch)
Return bodyOfTextToSearch.Substring(j + 1, k - j - 1)
End Function
Private Sub btnShowTroubleshooting_Click(sender As Object, e As EventArgs) Handles btnShowTroubleshooting.Click
Dim allErrorText As String = ReadEmbeddedTextFileResource(My.Resources.FanucCodes)
Dim errorMessage As String = FindTextBetweenBars(allErrorText, "|ACAL-000")
If errorMessage Is Nothing Then errorMessage = "Error code Not found!"
RichTextBoxFanucFaults.Text = errorMessage
End Sub
Here is a function that should do what you want:
Function FindTextBetweenBars(bodyOfTextToSearch As String, textToLookFor As String) As String
Dim i As Integer = bodyOfTextToSearch.IndexOf(textToLookFor)
If i < 0 Then Return Nothing
Dim j As Integer = bodyOfTextToSearch.LastIndexOf("|", i)
Dim k As Integer = bodyOfTextToSearch.IndexOf("|", i + Len(textToLookFor))
If k < 0 Then k = Len(bodyOfTextToSearch)
Return bodyOfTextToSearch.Substring(j + 1, k - j - 1)
End Function
In your button click event handler you can call the function like this:
Dim errorMessage as String = FindTextBetweenBars(My.Resources.FanucCodes, txtErrorCodeToLookFor.Text)
If errorMessage Is Nothing Then errorMessage = "Error code not found!"
txtErrorMessage.Text = errorMessage
where txtErrorMessage is the output textbox to display the error message result,
My.Resources.FanucCodes is your large string resource containing all the error descriptions (with | separators), and txtErrorCodeToLookFor is a textbox that accepts the error code input from the user.

Help Visual Basic mixing characters

I'm making an application that will change position of two characters in Word.
Imports System.IO
Module Module1
Sub Main()
Dim str As String = File.ReadAllText("File.txt")
Dim str2 As String() = Split(str, " ")
For i As Integer = 0 To str2.Length - 1
Dim arr As Char() = CType(str2(i), Char())
For ia As Integer = 0 To arr.Length() - 1 Step 2
Dim pa As String
pa = arr(ia + 1)
arr(ia + 1) = arr(ia)
arr(ia) = pa
Next ia
For ib As Integer = 0 To arr.Length - 1
Console.Write(arr(ib))
File.WriteAllText("File2.txt", arr(ib))
Next ib
File.WriteAllText("File2.txt", " ")
Console.Write(" ")
Next i
Console.Read()
End Sub
End Module
For example:
Input: ab
Output: ba
Input: asdasd asdasd
Output: saadds saadds
Program works good, it is mixing characters good, but it doesn't write text to the file. It will write text in console, but not in file.
Note: Program is working only with words that are divisible by 2, but it's not a problem.
Also, it does not return any error message.
Your code is overwriting the file that you have already written with a single space (" ") each time round.
You should only open the file once, and append to it using a stream writer:
Using output = File.CreateText("file2.txt")
' Put the for loop here.
End Using
There are some other things wrong with your code. Firstly, use For Each instead of For, this makes your code much more simple and readable. Secondly, try to avoid For loops altogether where possible. For instance, instead of iterating over the characters to output them one at a time, just create a new string from the char array, and write that:
Dim shuffledWord As New String(arr)
output.Write(shuffledWord)
Some of your types are plain wrong, i.e. you are using String in places instead of Char. You should always use Option Strict On. Then the compiler will not tolerate such code.
You should also prefer to use framework methods over VB-specific methods. This makes it easier to understand for C# programmers, and also makes it easier to translate and change (that is, use the Split method of strings instead of a free function, use ToCharArray instead of a cast to Char() …).
Finally, use meaningful variable names. str, str2 and arr are particularly cryptic because they don’t tell the reader of the code anything of interest about the variables.
Sub Main()
Dim text As String = File.ReadAllText("File.txt")
Dim words As String() = str.Split(" "c)
Using output = File.CreateText("file2.txt")
For Each word In words
dim wordChars = word.ToCharArray()
For i As Integer = 0 To wordChars.Length - 1 Step 2
Dim tmp As Char = wordChars(i + 1)
wordChars(i + 1) = wordChars(i)
arr(i) = tmp
Next
Dim shuffledWord As New String(wordChars)
output.Write(shuffledWord + " ")
Console.Write(huffledWord + " ")
Next
End Using
Console.Read()
End Sub