我正在尝试从字符串中“提取”一个数字,使用以下简单代码将字符串拆分为:
,然后只使用结果的前几个字符。然而,实际的真实世界字符串包含两个以:
开头的数字,我只想从字符串中拉出其中一个,但这导致了一些问题。我正在尝试从字符串的以下部分中提取数字:Our Ref: 200018
但是split函数似乎只支持从中拆分一个字符。在现实世界中,这个数字变化很大,但长度保持相同的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)
在代码中与其混淆?
{{1}}
答案 0 :(得分:1)
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个第一个Chars:
Dim str As String = wordArr(1).Substring(0,7)
更多信息:Here
答案 1 :(得分: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 rEF
或OUR REF
(等)。
模式解释:
\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.
比赛组是&#34;子比赛&#34;可以通过Match.Groups(<group index>).Value
访问哪些值。组索引0是整个匹配。
了解更多: