Re: Find instance in a string
From: Jay B. Harlow [MVP - Outlook] (Jay_Harlow_MVP_at_msn.com)
Date: 05/27/04
- Next message: jcrouse: "Re: Getting text from within a string"
- Previous message: Jay B. Harlow [MVP - Outlook]: "Re: Overriding .Enabled"
- In reply to: Chris Thunell: "Find instance in a string"
- Next in thread: Jay B. Harlow [MVP - Outlook]: "Re: Find instance in a string"
- Messages sorted by: [ date ] [ thread ]
Date: Wed, 26 May 2004 19:00:49 -0500
Chris,
I would use a RegEx as the others stated, something like:
Private Shared Function FindNumber(ByVal input As String) As String
Static exp As New Regex("\d{4}", RegexOptions.Compiled)
Dim match As Match = exp.Match(input)
Return match.Groups(0).Value
End Function
Public Shared Sub Main()
Debug.WriteLine(FindNumber("0104 PBR"), "0104 PBR")
Debug.WriteLine(FindNumber("PBR XT 0105 TD"), "PBR XT 0105 TD")
Debug.WriteLine(FindNumber("PBR XT 105 TD"), "PBR XT 105 TD")
End Sub
If there is no 4 character number in the input, an empty string is returned
otherwise the string itself is returned. If there are more then a single
instance of 4 numbers only the first is returned.
If you need multiple matches you can use Match.Success & Match.NextMatch in
a loop, or I believe John's code.
Dim match As Match = exp.Match(input)
Do While match .Success
Debug.WriteLine(match.Groups(0).Value, input)
match = match.NextMatch()
Loop
The following sites provide a wealth of information on regular expressions.
A tutorial & reference on using regular expressions:
http://www.regular-expressions.info/
The MSDN's documentation on regular expressions:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconRegularExpressionsLanguageElements.asp
Hope this helps
Jay
"Chris Thunell" <cthunell@pierceassociates.com> wrote in message
news:O1rikEzQEHA.1624@TK2MSFTNGP09.phx.gbl...
> I'm looking to find in a long string an instance of 4 numbers in a row,
and
> pull out those numbers.
> For instance:
> string = "0104 PBR", i'd like to get the 0104.
> string="PBR XT 0105 TD", i'd like to get the 0105.
> The numbers will always be 4 digits together.
> (I'm using vb.net)
> Any help would be greatly appreciated!
> Chris
> cthunell@pierceassociates.com
>
>
- Next message: jcrouse: "Re: Getting text from within a string"
- Previous message: Jay B. Harlow [MVP - Outlook]: "Re: Overriding .Enabled"
- In reply to: Chris Thunell: "Find instance in a string"
- Next in thread: Jay B. Harlow [MVP - Outlook]: "Re: Find instance in a string"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|