在这样的字符串中,如何提取前面的数字?
我现在字段里有这样的字符串,如:1 x535,1 x 535L,1x 5204,2 x 4345这样的字符串里,如何提取得到最前面的数字。因为这个数字后跟空格,再跟x,再有空格?是不是字符串匹配的内容?
[解决办法]
试试:CStr(Val("1 x535"))
[解决办法]
Private Sub Form_Load()
Dim dic As Object, tmp
Dim strData As String
Dim reg As Object
Dim matchs As Object, match As Object
strData = "1 x 5503,2x 3402" & vbCrLf & _
"2 x 231" & vbCrLf & _
"1 x 4602" & vbCrLf & _
"1 x 2121" & vbCrLf & _
"1 x 1290" & vbCrLf & _
"2 x 5503" & vbCrLf & _
"1 x 4602" & vbCrLf & _
"1 x 2121" & vbCrLf & _
"1 x 231"
Set dic = CreateObject("scripting.dictionary")
Set reg = CreateObject("vbscript.regExp")
reg.Global = True
reg.Pattern = "(\d+)\s*x\s*(\d+)"
Set matchs = reg.Execute(strData)
For Each match In matchs
dic(match.SubMatches(1)) = dic(match.SubMatches(1)) + Val(match.SubMatches(0))
Next
For Each tmp In dic.keys
Debug.Print tmp & vbTab & dic(tmp)
Next
End Sub
Option Explicit
Private Declare Function SendMessagebyString Lib _
"user32" Alias "SendMessageA" (ByVal hWND As Long, _
ByVal wMsg As Long, ByVal wParam As Long, _
ByVal lParam As String) As Long
Private Const LB_FINDSTRINGEXACT = &H1A2
Private Sub Command1_Click()
Dim strData As String
Dim strLine() As String, strItem() As String, strPara() As String
Dim i As Long, j As Long, n As Long
strData = Text1
strData = Replace(strData, "X", "x")
strData = Replace(strData, " ", "")
strLine = Split(strData, vbCrLf)
List1.Clear
For i = 0 To UBound(strLine)
strItem = Split(strLine(i), ",")
For j = 0 To UBound(strItem)
strPara = Split(strItem(j), "x")
If UBound(strPara) = 1 Then
n = SendMessagebyString(List1.hWND, LB_FINDSTRINGEXACT, -1, strPara(1))
If n = -1 Then
List1.AddItem strPara(1)
List1.ItemData(List1.NewIndex) = Val(strPara(0))
Else
List1.ItemData(n) = List1.ItemData(n) + Val(strPara(0))
End If
End If
Next j
Next i
'show result
For i = 0 To List1.ListCount - 1
Debug.Print List1.List(i), List1.ItemData(i)
Next i
End Sub
Private Sub Form_Load()
Text1 = "1 x 5503,2x 3402" & vbCrLf & _
"2 x 231" & vbCrLf & _
"1 x 4602" & vbCrLf & _
"1 x 2121" & vbCrLf & _
"1 x 1290" & vbCrLf & _
"2 x 5503" & vbCrLf & _
"1 x 4602" & vbCrLf & _
"1 x 2121" & vbCrLf & _
"1 x 231"
List1.Visible = False
End Sub
5503 3
3402 2
231 3
4602 2
2121 2
1290 1