VB.net ищет термины в строке?

    Dim keys1() As String = {"corrupt", "selfish", "power", "lying", "lies", "media"}
    Dim terms1 As Integer = 0
    Dim terms1string As String = ""
    terms1string = Console.ReadLine()
    For Each st As String In keys1
        terms1 = terms1 + 1
    Next
    If terms1 < 2 Then
        Console.WriteLine("yay!")
    Else
        Console.WriteLine("YouFail")
    End If

Вот мой код. Я бы хотел, чтобы, если введенная вами строка содержала более двух таких терминов, она писала «Yay», иначе она писала «YouFail».

---обновление 29.08.12---

    Function StageTwo(ByVal fname, ByVal lname, ByVal city)
    Console.WriteLine("Describe the U.S. Government.")
    Dim overall As Integer = 0
    Dim keys1() As String = {"corrupt", "selfish", "power", "lying", "lies", "media"}
    Dim terms1 As Integer = 0
    Dim terms1string As String = ""
    terms1string = Console.ReadLine()
    For Each st As String In keys1
        If InStr(terms1string, st) > 0 Then '<<<this line right here!
            terms1 = terms1 + 1
        End If
    Next
    If terms1 < 0 Then
        Console.WriteLine("yay!")
        overall = overall + 1
    End If
    Console.WriteLine()
    Console.WriteLine("Describe the economic status in the U.S.")
    Dim keys2() As String = {"broken", "backed", "failed", "skewed", "tilted", "99%", "rigged", "unfair"}
    Dim terms2 As Integer = 0
    Dim terms2string As String = ""
    terms2string = Console.ReadLine()
    For Each st As String In keys2
        If InStr(terms2string, st) > 0 Then '<<<this line right here!
            terms2 = terms2 + 1
        End If
    Next
    If terms2 < 0 Then
        Console.WriteLine("yay!")
        overall = overall + 1
    End If
    If overall = 2 Then
        Console.WriteLine()
        Console.WriteLine("Enter a username.")
        Dim username As String = ""
        username = Console.ReadLine()
        Console.WriteLine("Please wait.")
        IsURLValid(username, overall)
    Else
        Console.WriteLine("Test Failed.")
    End If
    System.Threading.Thread.Sleep(2000)
End Function

Это мой свежий код. Все еще не работает, тест печати не прошел после ввода поврежденного для первого и сломанного для второго. Помочь снова? Большое спасибо, ребята.


person Jay Noe    schedule 29.08.2012    source источник
comment
Посмотрите на RegEx. Это что-то вроде кривой обучения, но определенное вложение.   -  person Michael Rodrigues    schedule 29.08.2012


Ответы (4)


Почему так сложно? Просто используйте Count:

Dim keys1() As String = {"corrupt", "selfish", "power", "lying", "lies", "media"}
Dim terms1string = Console.ReadLine()

Dim terms1 = keys1.Count(function(key) terms1string like "*" & key & "*")

If terms1 < 2 Then
    Console.WriteLine("yay!")
Else
    Console.WriteLine("YouFail")
End If

Если вы хотите сопоставить отдельные слова (foobar power lies — 2 совпадения, foobarpowerlies — 0 совпадений), вы можете вместо этого использовать эту строку:

Dim terms1 = keys1.Count(function(key) terms1string.Split().Contains(key))

Для полноты здесь версия регулярного выражения:

' generous match ('foobarpowerlies' => 2 matches)
Dim pattern = String.Join("|", keys1)
Dim terms1 = Regex.Matches(terms1string, pattern).Count

or

' strict match using word boundaries ('foobarpowerlies' => 0 matches, but 'foobar power lies' => 2 matches)
Dim pattern = String.Join("|", keys1.Select(function(key) "\b" & key & "\b"))
Dim terms1 = Regex.Matches(terms1string, pattern).Count
person sloth    schedule 29.08.2012

Должен ли «Остин Пауэрс» соответствовать «власти», а «некоррумпированный» — «коррумпированному»? Предположим, что "нет"
Должно ли "МОЩНОСТЬ" соответствовать "мощности"? Предполагая "да"

Самый безопасный способ сделать это с помощью Regex

Function WordCount(keys() As String, terms As String) As Integer
    Dim pattern As String = "\b(" + Regex.Escape(keys(0))
    For Each key In keys.Skip(1)
        pattern += "|" + Regex.Escape(key)
    Next
    pattern += ")\b"

    Return Regex.Matches("terms", pattern, RegexOptions.IgnoreCase).Count
End Function


Sub Main()
    Dim keys1() As String = {"corrupt", "selfish", "power", "lying", "lies", "media"}
    Dim count As Integer
    count = WordCount(keys1, "lying son of a corrupt . . .") ' returns 2
    count = WordCount(keys1, "Never caught lying and uncorrupt . . .") ' returns 1
End Sub

Функция Regex.Escape гарантирует, что любые специфические символы Regex в ваших ключах будут экранированы и не будут рассматриваться как команды Regex.

Параметр RegexOptions.IgnoreCase указывает ему выполнять поиск без учета регистра.

\b является границей слова, поэтому должна быть граница слова (пробел, пунктуация, новая строка, начало строки, конец строки и т. д.) до и после совпадения.

Помещение ключей в эту структуру (key1|key2|key3) говорит, что она может совпадать с key1 или key2 или key3

Надеюсь это поможет

person Binary Worrier    schedule 29.08.2012

У меня есть кое-что для тебя.

INSTR() вашего отца. Это оружие хакера QuickBasic 4.5. Не такой неуклюжий или случайный, как регулярное выражение; элегантное оружие для более цивилизованного века.

Module Module1

  Sub Main()
    Dim keys1() As String = {"corrupt", "selfish", "power", "lying", "lies", "media"}
    Dim terms1 As Integer = 0
    Dim terms1string As String = ""
    terms1string = Console.ReadLine()
    For Each st As String In keys1
      If InStr(terms1string, st) > 0 Then '<<<this line right here!
        terms1 = terms1 + 1
      End If
    Next st
    If terms1 < 2 Then
      Console.WriteLine("yay!")
    Else
      Console.WriteLine("YouFail")
    End If
    Console.ReadKey()

  End Sub

End Module
person SSS    schedule 29.08.2012

Возможно, слишком упрощенно, но если вы используете IndexOf, вы можете изменить цикл For на:

    If Not String.IsNullOrEmpty(terms1string) Then
        For Each st As String In keys1
            If terms1string.IndexOf(st) <> -1 Then
                terms1 = terms1 + 1
            End If
        Next
    End If

Это упрощение в том, что он не токенизирует входные данные... поэтому такие слова, как «коррупция» и «неверные», будут регистрировать совпадение. Если вам нужны точные совпадения, взгляните на String.Split, чтобы получить входные слова, а затем есть ряд алгоритмических опций для сравнения этого списка с вашим списком ключей.

person Jim O'Neil    schedule 29.08.2012