只获取包含给定单词VB2010.net的文本行

时间:2012-06-03 15:22:10

标签: vb.net

我的网站上有一个文本文件,我通过webclient.downloadstring下载整个字符串。

文本文件包含:

饼干,菜肴,糖果,(新行) 后退,前进,刷新,(新线) 邮件,媒体,静音,

这只是一个例子,它不是实际的字符串,但它可以用于帮助目的。

我想要的是我想要下载整个字符串,找到包含用户在textbox中输入的单词的行,将该行转换为字符串,然后我想使用该字符串.split with as delimiter“,”并将字符串中的每个单词输出为richtextbox

现在这里是我使用过的代码(出于隐私原因,删除了一些字段)。

If TextBox1.TextLength > 0 Then
        words = web.DownloadString("webadress here")
        If words.Contains(TextBox1.Text) Then
            'retrieval code here
            Dim length As Integer = TextBox1.TextLength
            Dim word As String
            word = words.Substring(length + 1) // the plus 1 is for the ","
            Dim cred() As String
            cred = word.Split(",")
            RichTextBox1.Text = "Your word: " + cred(0) + vbCr + "Your other word: " + cred(1)
        Else
            MsgBox("Sorry, but we could not find the word you have entered", MsgBoxStyle.Critical)
        End If
    Else
        MsgBox("Please fill in an word", MsgBoxStyle.Critical)
    End If

现在它可以工作但没有错误,但它只适用于第1行,而不适用于第2行或第3行

我做错了什么?

2 个答案:

答案 0 :(得分:0)

这是因为字符串words还包含您似乎在代码中省略的新行字符。您应首先将words与分隔符\n(或\r\n分开,具体取决于平台),如下所示:

Dim lines() As String = words.Split("\n")

之后,你有一个字符串数组,每个元素代表一行。像这样循环:

For Each line As String In lines
    If line.Contains(TextBox1.Text) Then
        'retrieval code here
    End If
Next

答案 1 :(得分:0)

Smi的回答是正确的,但由于您使用的是VB,因此您需要拆分vbNewLine。 \ n和\ r \ n用于C#。我被这很多人绊倒了。

另一种方法是使用正则表达式。正则表达式匹配既可以找到您想要的单词,也可以在一个步骤中返回包含它的行。

以下几个经过测试的样本。我无法弄清楚你的代码是否按照你说的那样做了,所以我根据你的描述进行了即兴创作。

Imports System.Text.RegularExpressions

Public Class Form1

    Private Sub ButtonFind_Click(sender As System.Object, e As System.EventArgs) Handles ButtonFind.Click

        Dim downloadedString As String
        downloadedString = "cookies,dishes,candy," _
             & vbNewLine & "back,forward,refresh," _
             & vbNewLine & "mail,media,mute,"

        'Use the regular expression anchor characters (^$) to match a line that contains the given text.
        Dim wordToFind As String = TextBox1.Text & ","  'Include the comma that comes after each word to avoid partial matches.
        Dim pattern As String = "^.*" & wordToFind & ".*$"
        Dim rx As Regex = New Regex(pattern, RegexOptions.Multiline + RegexOptions.IgnoreCase)

        Dim M As Match = rx.Match(downloadedString)
        'M will either be Match.Empty (no matching word was found), 
        'or it will be the matching line.

        If M IsNot Match.Empty Then
            Dim words() As String = M.Value.Split(","c)
            RichTextBox1.Clear()
            For Each word As String In words
                If Not String.IsNullOrEmpty(word) Then
                    RichTextBox1.AppendText(word & vbNewLine)
                End If
            Next
        Else
            RichTextBox1.Text = "No match found."
        End If

    End Sub

End Class