.net 从字符串中解析数字
我有以下字符串格式,可以有以下格式.net 从字符串中解析数字,.net,regex,vb.net,.net,Regex,Vb.net,我有以下字符串格式,可以有以下格式 2Y11M23D4H means Y=2,M=11,D=23,H=4 11Y2M11D19H means Y=11,M=2,D=11,H=19 3Y4H Y=3,H=4 51H H=51 我使用的是vb.net,我想将数字保存到变量中,正如您在上面的示例中看到的,每个数字都与后面的变量相关,我的问题是我找不到一个好方法来获取字符前面的数值 我想把总天数算作双倍 以下代码仅适用于每个字符前的单个数字 I
2Y11M23D4H means Y=2,M=11,D=23,H=4
11Y2M11D19H means Y=11,M=2,D=11,H=19
3Y4H Y=3,H=4
51H H=51
我使用的是vb.net,我想将数字保存到变量中,正如您在上面的示例中看到的,每个数字都与后面的变量相关,我的问题是我找不到一个好方法来获取字符前面的数值
我想把总天数算作双倍
以下代码仅适用于每个字符前的单个数字
If periodstring.Contains("Y") Then
totaldays += Convert.ToDouble(periodstring.Substring(periodstring.IndexOf("Y") - 1).First) * 365
End If
If periodstring.Contains("M") Then
totaldays += Convert.ToDouble(periodstring.Substring(periodstring.IndexOf("M") - 1).First) * 30
End If
If periodstring.Contains("D") Then
totaldays += Convert.ToDouble(periodstring.Substring(periodstring.IndexOf("D") - 1).First)
End If
If periodstring.Contains("H") Then
totaldays += Convert.ToDouble(periodstring.Substring(periodstring.IndexOf("H") - 1).First) / 24
End If
这是一个最好的候选人。类似这样的方法会奏效:
Dim rex as RegEx
rex = new RegEx("(\d+)(\w+)")
Dim startPos as Int
Dim m as Match
startPos = 0
Do
m = rex.Match(inputString, startPos)
If(m.Success) Then
' m.Groups(1) will contain the digits
' m.Groups(2) will contain the letter
startPos = startPos + m.Length
End if
While(m.Success)
正则表达式包含两个组:\d+和\w+。第一组匹配一组数字,第二组匹配一组字母
只要正则表达式匹配,就可以匹配字符串,并继续提取数字组和字母组。并相应地分析它们
查看此项,可以开始使用Match类在VB.net中使用正则表达式提取匹配项。这是一个主要的候选项。类似这样的方法会奏效:
Dim rex as RegEx
rex = new RegEx("(\d+)(\w+)")
Dim startPos as Int
Dim m as Match
startPos = 0
Do
m = rex.Match(inputString, startPos)
If(m.Success) Then
' m.Groups(1) will contain the digits
' m.Groups(2) will contain the letter
startPos = startPos + m.Length
End if
While(m.Success)
正则表达式包含两个组:\d+和\w+。第一组匹配一组数字,第二组匹配一组字母
只要正则表达式匹配,就可以匹配字符串,并继续提取数字组和字母组。并相应地分析它们
查看此项可以快速开始使用Match类在VB.net中使用正则表达式提取匹配