在VB.Net中拆分字符串,但仅当满足特定格式时
我有下面的代码来拆分字符串,但有时它会拆分我不想拆分的单词 例如,它将拆分“LFMT”,但我只希望它拆分一个格式为“FM123456”的字符串 代码如下在VB.Net中拆分字符串,但仅当满足特定格式时,vb.net,string,replace,split,format,Vb.net,String,Replace,Split,Format,我有下面的代码来拆分字符串,但有时它会拆分我不想拆分的单词 例如,它将拆分“LFMT”,但我只希望它拆分一个格式为“FM123456”的字符串 代码如下 Dim strSplitTAF() = New String() {"TEMPO", "PROB30", "PROB40", "BECMG", "FM"} For Each strWord As String In strSplitTAF strTAF = strTAF.Replace(strWord, Environment.New
Dim strSplitTAF() = New String() {"TEMPO", "PROB30", "PROB40", "BECMG", "FM"}
For Each strWord As String In strSplitTAF
strTAF = strTAF.Replace(strWord, Environment.NewLine & strWord)
Next
你有什么想法吗
提前感谢。要检查格式是否正确,请使用以下条件
If Str1.Length = 8 AndAlso Str1.Substring(0, 2) = "FM" AndAlso IsNumeric(Str1.Substring(2, 6)) Then
'The code goes here
End If
用格式为“FM123456”的变量替换Str1
编辑
检查这是否是你想要的
'Test data for strTAF
Dim strTAF As String = "TEMPO Test1 PROB30 Test2 PROB40 Test3 BECMG Test4 FM123456 Test5 LFMT Test6 FM654321 Test7 FM124"
'FM is removed since it will use a specific condition to split the string (FM + 6 numbers)
Dim strSplitTAF() = New String() {"TEMPO", "PROB30", "PROB40", "BECMG"}
For Each strWord As String In strSplitTAF
strTAF = strTAF.Replace(strWord, Environment.NewLine & strWord)
Next
'Removes the new line on the first line (optional)
strTAF = strTAF.Trim
'Finds the index of the first FM in the string
Dim Index As Integer = strTAF.IndexOf("FM")
While Index > -1
'Checks if the index + 8 (FM + 6 numbers) exceeds the length of the strTAF
If Index + 8 <= strTAF.Length Then
'Checks if the string (consecutive 6 chars) after FM is numeric
If IsNumeric(strTAF.Substring(Index + 2, 6)) Then
strTAF = strTAF.Substring(0, Index) & Environment.NewLine & strTAF.Substring(Index)
End If
Else
Exit While
End If
'Gets the new index of FM
Index = strTAF.IndexOf("FM", Index + 8)
End While
STRAF的测试数据
Dim strTAF As String=“节奏测试1 PROB30测试2 PROB40测试3 BECMG测试4 FM123456测试5 LFMT测试6 FM654321测试7 FM124”
'FM已删除,因为它将使用特定条件拆分字符串(FM+6个数字)
Dim strSplitTAF()=新字符串(){“TEMPO”、“PROB30”、“PROB40”、“BECMG”}
将每个strWord作为strSplitTAF中的字符串
straf=straf.Replace(strWord、Environment.NewLine和strWord)
下一个
'删除第一行上的新行(可选)
straf=straf.修剪
'查找字符串中第一个FM的索引
作为整数的Dim索引=straf.IndexOf(“FM”)
而索引>-1
'检查索引+8(FM+6数字)是否超过straf的长度
如果索引+8,您希望使用该格式拆分字符串,例如:FM+(数字),或者该字符串可以以数字开头?它将始终以FM后跟6个数字。