如何在字符串中搜索整数

时间:2014-01-04 02:33:09

标签: vb.net string integer

我正在创建一个程序,当输入是非结构化时,它将为您提供总和的结果。请参阅以下内容:

输入:

whats 20 + 26

输出:

46

我已经知道如何搜索字符串中的文字(If text.IndexOf("hello") >= 0 Then)......

我不知道如何使用两个整数作为加法方程式。

2 个答案:

答案 0 :(得分:0)

以下是如何使用正则表达式开始执行此操作的快速示例。这对你投掷的任何东西都不会是防弹的,但它应该是一个良好的开端。

请务必将Imports System.Text.RegularExpressions添加到.vb文件

    'This string is an example input.  It demonstrates that the method below 
    'will find the sum "2345+ 3256236" but will skip over things like 
    '  if + .04g
    '  1.23 + 4
    ' etc...
    Dim input As String = _   
       "aoe%rdes 2345+ 3256236 if + .04g  rcfo 8 3 . 1.23 + 4 the#r whuts"

    Dim pattern As String = "\s\d+\s*\+\s*\d+(?=\s|$)"
    For Each _match As Match In Regex.Matches(input, pattern)
        Dim a = _match.Value.Split("+"c)  'Match extracts "2345+ 3256325"
        Dim x As Integer                
        Dim y As Integer
        If Integer.TryParse(a(0), x) AndAlso Integer.TryParse(a(1), y) Then
            Console.WriteLine("Found the Sum : " & x & " + " & y)
            Console.WriteLine("Sum is : " & x + y)
        Else
            Console.WriteLine("Match failed to parse")
        End If
    Next

正则表达式可以细分为

\s        '(definitely) one whitespace
\d+       'followed by any number of integer digits
\s*       'followed by (possibly) a whitespace
\+        'followed by (definitely) a "+"
\s*       'followed by (possibly) a whitespace
\d+       'followed by any number of integer digits
(?=\s|$)  'followed by (definitely) either a whitespace or EOL

在这里阅读更多内容:

Regular Expression Language - Quick Reference

.NET Framework Regular Expressions

Regular Expressions Reference

答案 1 :(得分:-1)

将两个整数解析为两个整数变量 - 我们称之为xy。然后添加他们的结果。

Dim x as Integer
Dim y as Integer
Dim result as Integer

'parse your integers- you indicate you already know how to do this

'add the results
result = x + y

'now print out the result
相关问题