【问题标题】:VB.Net Get characters from after certain wordsVB.Net 从某些单词之后获取字符
【发布时间】:2017-04-25 16:28:53
【问题描述】:

我试图从字符串中“提取”一个数字,方法是使用以下简单代码在: 处拆分字符串,然后只使用结果的前几个字符。然而,实际的现实世界字符串包含两个数字,前面有一个 :,我只想从字符串中拉出其中一个,但这给我带来了一些问题。我正在尝试从字符串的以下部分中提取数字:Our Ref: 200018 但拆分功能似乎只支持一个字符进行拆分。在现实世界中,这个数字变化很大,但长度保持不变 8 个字符。

我怎样才能只从Our Ref: 200018 中提取数字而不 Your Ref: 265845 在代码中与它混淆?

Dim sOutput As String = "This is an example string Our Ref: 200018 Your Ref: 265845 did this work?"
Dim word As String = sOutput
Dim wordArr As String() = word.Split(":")
MsgBox("Result: " & wordArr(1).ToString)

【问题讨论】:

    标签: string vb.net split


    【解决方案1】:

    你可以使用Regex:

    Dim sOutput As String = "This is an example string Our Ref: 200018 Your Ref: 265845 did this work?"
    Dim m As Match = Regex.Match(sOutput, "\bOur Ref\b\:\s*(\d+)", RegexOptions.IgnoreCase)
    
    If m.Success = True Then 'Match found.
        Dim Ref As Integer = Integer.Parse(m.Groups(1).Value)
        MessageBox.Show(Ref)
    End If
    

    需要进口:

    Imports System.Text.RegularExpressions
    

    此代码不区分大小写,因此它也会匹配 oUr rEFOUR REF(等)。

    在线测试:http://ideone.com/DetTxq

    模式解释:

    \bOur Ref\b\:\s*(\d+)
    
    \b         =>  Word boundary, means that it should match whole words (i.e. only "Our Ref" and not "Your Ref", etc.).
    Our Ref    =>  Match the words "Our Ref".
    \:         =>  Match a colon.
    \s*        =>  Match zero or more spaces.
    (          =>  Start of match group.
        \d+    =>  Match one or more numerical characters.
    )          =>  End of match group.
    

    匹配组是“子匹配”,其值可以通过Match.Groups(<group index>).Value 访问。组索引 0 是整个匹配项。

    阅读更多:

    【讨论】:

    • 谢谢,这是我得到的最好的答案之一,最详细和最有帮助的答案。事实证明,您的回答非常有用,并且您帮助我更好地理解 Regex,因为我是一名自学成才的编码员。非常感谢。
    • @user3516240 :很高兴我能提供帮助,我的回答让您满意!有趣的巧合:我也是自学的。 :)
    • @user3516240 :我刚刚注意到如果它出现在Our Ref: 之前,它也会匹配Your Ref:。我已经编辑了我的答案以进行修复,以便它匹配 Our Ref: only
    【解决方案2】:
    Dim sOutput As String = "This is an example string Our Ref: 200018 Your Ref: 265845 did this work?"
    Dim word As String() = New String() {"Our Ref: "} 
    Dim wordArr As String() = sOutput.Split(word,StringSplitOptions.RemoveEmptyEntries)
    

    然后从示例中的子字符串中取出前 8 个字符:

    Dim str As String = wordArr(1).Substring(0,7)
    

    更多信息:Here

    【讨论】:

    • 你为什么使用String.JoinwordArr(1) 是单个字符串,而不是数组。
    • 你是对的。这里可以直接使用Dim str As String = wordArr(1).Substring(0,7)。已编辑:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多