Parse a string

S

Sarah

Does anyone know how I could parse a string that either looks like

RA010R01
or
R010R01

for the numeric string 010? This is not always the same. It could also
look like

R020R01

Thank you.

Sarah
 
J

JvC

I'm guessing you want to extract the numeric portion, so
Public function GetNumbers(MyString as string) as string
dim Fragment as string
dim MyChar as string
MyChar = left(MyString, 1)
do while len(Fragment) < 3
if isnumeric(MyChar) and len(Fragment) < 3 then
Fragment = Fragment & MyChar
endif
MyString = right(MyString, Len(Mystring) - 1)
MyChar = left(MyString, 1)
loop
GetNumbers = Fragment
end function

This just works for extracting the 3 numerics. Other variations are
possible.

Sarah has brought this to us :
 
S

Sarah

Thank you. Yours is the best solution. Since the numeric portion can also
be 2 digits only. I can work with what you gave me.

Thanks again!
 
J

John W. Vinson

Does anyone know how I could parse a string that either looks like

RA010R01
or
R010R01

for the numeric string 010? This is not always the same. It could also
look like

R020R01

"Not always the same" is ambiguous. Might it be RRRR010R01 (010)? RA00025R01
(00025)?

What commonality is there? Will the number to be extracted always have three
digits?
 
D

DaveT

Nothing on TV so here goes. This gives results such as:

ParseIT("R0101R01") = 0101
ParseIT("R010R01") = 010

etc...


If the pattern is find first occurrence of a string of numbers within a
string then:

Public Function ParseIT(y)
Const strNumbers As String = "0123456789"

Dim strIN As String
Dim strTMP As String
Dim a As String

Dim zLen As Long

Dim iCounter As Long
Dim jCounter As Long

Dim blnFlag As Boolean

On Error GoTo TrapIt


If Len(Nz(y)) = 0 Then 'nothing to do
Exit Function

Else
strIN = y
zLen = Len(strIN)
End If

strTMP = ""
blnFlag = False

For iCounter = 1 To zLen
a = Mid(strIN, iCounter, 1)

If InStr(strNumbers, a) > 0 Then 'found first occurrence of number

strTMP = a

If iCounter = zLen Then 'rare case than only number is at end
Exit For
End If


For jCounter = iCounter + 1 To zLen 'run to end of string
a = Mid(strIN, jCounter, 1)

If InStr(strNumbers, a) > 0 Then
strTMP = strTMP & a

Else 'bail out if we find another alpha
blnFlag = True
Exit For
End If
Next jCounter


End If

If blnFlag Then Exit For

Next iCounter

ParseIT = strTMP

EnterHere:

Exit Function

TrapIt:
MsgBox Err.Number & vbCrLf & Err.Description
Resume EnterHere

End Function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top