如何在字符串中查找数值

时间:2013-02-20 15:40:48

标签: vb.net artificial-intelligence information-retrieval information-extraction

我正在尝试创建一个分析文本字符串的方法,以查看它是否包含数值。例如,给定以下字符串:

  

什么是2 * 2?

我需要确定以下信息:

  • 该字符串包含数值:True
  • 它包含的数值是什么:2(其中任何一个都应该使函数返回true,我应该将字符串中每个2的位置放在一个变量中,如位置0为第2)

这是我到目前为止的代码:

Public Function InQuestion(question As String) As Boolean
    ' Possible substring operations using the position of the number in the string?
End Function

1 个答案:

答案 0 :(得分:1)

这是一个示例控制台应用程序:

Module Module1
    Sub Main()
        Dim results As List(Of NumericValue) = GetNumericValues("What is 2 * 2?")
        For Each i As NumericValue In results
            Console.WriteLine("{0}: {1}", i.Position, i.Value)
        Next
        Console.ReadKey()
    End Sub

    Public Class NumericValue
        Public Sub New(value As Decimal, position As Integer)
            Me.Value = value
            Me.Position = position
        End Sub

        Public Property Value As Decimal
        Public Property Position As Integer
    End Class

    Public Function GetNumericValues(data As String) As List(Of NumericValue)
        Dim values As New List(Of NumericValue)()
        Dim wordDelimiters() As Char = New Char() {" "c, "*"c, "?"c}
        Dim position As Integer = 0
        For Each word As String In data.Split(wordDelimiters, StringSplitOptions.None)
            Dim value As Decimal
            If Decimal.TryParse(word, value) Then
                values.Add(New NumericValue(value, position))
            End If
            position += word.Length + 1
        Next
        Return values
    End Function
End Module

如您所见,它传递字符串“什么是2 * 2?”它输出每个数值的位置和值:

  

8:2

     

12:2