473,549 Members | 2,731 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Find instance in a string

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
ct******@pierce associates.com
Nov 20 '05 #1
7 3969
In article <O1************ **@TK2MSFTNGP09 .phx.gbl>,
ct******@pierce associates.com says...
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)


Look at String.IndexOf or VB's Instr() function.

--
Patrick Steele
Microsoft .NET MVP
http://weblogs.asp.net/psteele
Nov 20 '05 #2
Hi Chis,

I seldom say this, however this looks as a real Regex problem.
Something I do not like, so I changed the subject a little bit to get
attention from the ones who like Regex problems and that are a lot in this
newsgroup.

Cor
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

Nov 20 '05 #3
Hi Chris,

If you know the string you are looking for you can do String.IndexOf( )

On the other hand of you are looking for the first occurance of 4
consecutive numbers in a string you could do some regular expressions.

I have only tried this once in VB Script and I think its changed a bit
since. Your regular expression string can be something like
"[0-9]{4}"

You could also take the easier route and parse the string character by
charcater. But regular expressions will be more efficient.

--
Wazir
"Chris Thunell" <ct******@pierc eassociates.com > wrote in message
news:O1******** ******@TK2MSFTN GP09.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
ct******@pierce associates.com

Nov 20 '05 #4
>
I have only tried this once in VB Script and I think its changed a bit
since. Your regular expression string can be something like
"[0-9]{4}"

Just tried it and it works as expected.

Public Sub Foo(ByVal sInputString As String)
Dim r As New Regex("[0-9]{4}")
Dim m As Match = r.Match(sInputS tring)
If m.Success Then
Debug.WriteLine (m.Value)
Else
Debug.WriteLine ("No matches")
End If
End Sub

I hope that helps.

--
Wazir



Nov 20 '05 #5
"Chris Thunell" <ct******@pierc eassociates.com > wrote in message news:<O1******* *******@TK2MSFT NGP09.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
ct******@pierce associates.com


You want a regular expression, here.

Imports System.Text.Reg ularExpressions
Module Module1

Sub Main()

Call Test("0104 PBR")
Call Test("PBR XT 0105 TD")
Call Test("blah PER VB 0106")

Debug.Assert(Tr ue)

End Sub

Private Sub Test(ByVal StringToTest As String)

Dim re As New Regex("\s\d{4}\ s|^\d{4}\s|\s\d {4}$|^\d{4}$")
Dim mc As MatchCollection = re.Matches(Stri ngToTest)
Dim m As System.Text.Reg ularExpressions .Match

For Each m In mc
Console.WriteLi ne(Trim$(m.ToSt ring()))
Next
End Sub
End Module
(Note that there may be more elegant ways to form the expression, but
I ran into the problem that putting ^ in [] has a different meaning.
Please consult your friendly System.Text.Reg ularExpressions help
topics for more information.)

(Note also that \s matches not only spaces, but also tabs, formfeeds,
and so forth. If you're sure you only need spaces, then replace the
\s with a space.)

John Fiala
jcfiala523-at-hotmail.com
http://www.livejournal.com/users/fiala_tech/
Nov 20 '05 #6
Chris,
I would use a RegEx as the others stated, something like:

Private Shared Function FindNumber(ByVa l input As String) As String
Static exp As New Regex("\d{4}", RegexOptions.Co mpiled)
Dim match As Match = exp.Match(input )
Return match.Groups(0) .Value
End Function

Public Shared Sub Main()
Debug.WriteLine (FindNumber("01 04 PBR"), "0104 PBR")
Debug.WriteLine (FindNumber("PB R XT 0105 TD"), "PBR XT 0105 TD")
Debug.WriteLine (FindNumber("PB R 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/de...geElements.asp

Hope this helps
Jay

"Chris Thunell" <ct******@pierc eassociates.com > wrote in message
news:O1******** ******@TK2MSFTN GP09.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
ct******@pierce associates.com

Nov 20 '05 #7
Chris,
Doh! Here's an improved version of mine. (my earlier version would return
the first 4 numbers of a 5 or greater instance of a number.)

Private Shared Function FindNumber(ByVa l input As String) As String
Static exp As New Regex("(^|\D+)( ?'number'\d{4}) ($|\D+)",
RegexOptions.Co mpiled)
Dim m As Match = exp.Match(input )
Return m.Groups("numbe r").Value
End Function

Public Shared Sub Main()
Const test1 As String = "0104 PBR"
Const test2 As String = "PBR XT 0105 TD"
Const test3 As String = "PBR XT 105 TD"
Const test4 As String = "PBR 0104 XT 0105 TD"
Const test5 As String = "PBR XT 01050 TD"

Debug.WriteLine (FindNumber(tes t1), test1)
Debug.WriteLine (FindNumber(tes t2), test2)
Debug.WriteLine (FindNumber(tes t3), test3)
Debug.WriteLine (FindNumber(tes t4), test4)
Debug.WriteLine (FindNumber(tes t5), test5)
End Sub

The biggest difference between this one & John's is that I look for any non
numeric \D before or after the number, where as John looks for any
whitespace \s character.

See the links I gave earlier for further features of regular expressions.

Hope this helps
Jay

"Chris Thunell" <ct******@pierc eassociates.com > wrote in message
news:O1******** ******@TK2MSFTN GP09.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
ct******@pierce associates.com

Nov 20 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1487
by: Lothar Behrens | last post by:
Hi, this is an unusual question here, but I think, it is C++ related due to the fact that my code is written with it. I have written an ODBC wrapper that - if checked out with my last working tag - works fine. I have identified the reason, why the update of a column fails with updating the column with an empty string. I have corrected...
10
5289
by: Sean Berry | last post by:
I need to find the second to last occurence of a "." in a string. Basically I am taking a URL like http://this.is.mydomin.com/path/to/file.txt and want to extract /path/to/file.txt I thought I would be able to do it like this: ----------------------------------------------------
5
3008
by: Mike Labosh | last post by:
In VB 6, the Form_QueryUnload event had an UnloadMode parameter that let me find out *why* a form is unloading, and then conditionally cancel the event. In VB.NET, the Closing event passes a CancelEventArgs that lets me cancel the Close() operation, but is there still any way to find out *why* a form is closing? This app as a form that...
14
2027
by: inpuarg | last post by:
I want to find a & character using Regex. But not && How can i manage this in c# Quickfind window ? -------------------------------------------------- ne kadar yaşarsan yaşa sevdiğin kadardır ömrün :( --------------------------------------------------
1
4363
by: Allan Ebdrup | last post by:
I have a dynamic list of regular expressions, the expressions don't change very often but they can change. And I have a single string that I want to match the regular expressions against and find the first regular expression that matches the string. I've gor the regular expressions ordered so that the highest priority is first (if two or more...
2
2655
by: moondaddy | last post by:
I had to repost this because I had to update and change my msdn alias. I will re-ask the question and clarify a few things that were not clear before. This code is all executed on my dev machine running winXP sp2 and VS2005. I'm using a c# 2.0 winforms app which talks to a c#2.0 asp.net app that also contains 1 web service. Note: the...
0
2577
by: db2user24 | last post by:
I'm trying to invoke a DB2 stored procedure. The stored proc is coded in C and compiled to a shared library, which has been placed in the <DB2 dir>/functions directory. The platform is Linux (using 64 bit DB2 UDB). From the debug log it seems that the stored procedure can't be found, although I don't know why. I can see that the procedure name...
2
6644
by: karinmorena | last post by:
I'm having 4 errors, I'm very new at this and I would appreciate your input. The error I get is: Week5MortgageGUI.java:151:cannot find symbol symbol: method allInterest(double,double,double) Location: class Week5MortgageGUI Week5MortgageLogic allint = logic.allInterest(amount, term, rate); Week5MortgageGUI.java:152:cannot find symbol...
3
1193
by: srinivasan srinivas | last post by:
Hi, I have written a class which has some attributes. I want to know how do i find out the size of an instance of this class?? class T(object):     def __init__(self, fn_name, *args, **kwds):         self.fn_name = fn_name         self.args = args         self.kwds = kwds Thanks, Srini
0
7518
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7715
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7469
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7808
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3498
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3480
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1057
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
757
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.