VB.Net从字符串函数中提取数字 [英] VB.Net Extract numbers from string function

查看:1280
本文介绍了VB.Net从字符串函数中提取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的请求是一个可以通过搜索提取数字的数据。

例如:
animalsOwned | 4 会返回一个包含4的动物| 3 | 2 | 1 | 3 将会返回一个包含4的元素b

一个包含3,2,1,3的数组

这会让我在文件流读取器中更容易。
谢谢

解决方案

尝试使用正则表达式。

  Imports System.Text.RegularExpressions 
命名空间演示
Class Program
Shared Function Main(ByVal args As String())As Integer
Dim array As Integer()= ExtractIntegers(animals | 3 | 2 | 1 | 3)
For Each i在数组
Console.WriteLine(i)
下一个
返回0
结束函数
共享函数ExtractIntegers(ByVal输入为字符串)As Integer()
Dim pattern As String =animals(\ |(?< number> [0-9] +))*
Dim match As Match = Regex.Match(input,pattern)
Dim list作为新列表(整数)
如果match.Success然后
对于每个捕获作为捕获在match.Groups(数字)。捕获
list.Add(Integer.Parse(捕获。值))
下一个
结束如果
返回李st.ToArray()
结束函数
结束类
结束命名空间


My request is one that can extract a number somewhat by a search.

Example: animalsOwned|4 would return an containing "4"

animals|3|2|1|3 would return an array containing "3", "2", "1", "3"

This would make it easier for me during a file stream reader. Thank you

解决方案

Try regular expression. It's a powerful tool for simple text parsing.

Imports System.Text.RegularExpressions
Namespace Demo
    Class Program
        Shared Function Main(ByVal args As String()) As Integer
            Dim array As Integer() = ExtractIntegers("animals|3|2|1|3")
            For Each i In array
                Console.WriteLine(i)
            Next
            Return 0
        End Function
        Shared Function ExtractIntegers(ByVal input As String) As Integer()
            Dim pattern As String = "animals(\|(?<number>[0-9]+))*"
            Dim match As Match = Regex.Match(input, pattern)
            Dim list As New List(Of Integer)
            If match.Success Then
                For Each capture As Capture In match.Groups("number").Captures
                    list.Add(Integer.Parse(capture.Value))
                Next
            End If
            Return list.ToArray()
        End Function
    End Class
End Namespace

这篇关于VB.Net从字符串函数中提取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆