Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

get out the numbers - regex 1

Status
Not open for further replies.

jamert

Programmer
Dec 9, 2007
80
CA
Ok, thanks for everyone helping me so far, i have been working on this regex for quite some time. I got it working, but i'm thinking that their must be a simplier solution. i have a string that can look many ways, for example:
string telH = " asd833. 0000 cell ";
or
string telH = " 777 9999 C ";

I set a string telH to the numbers that could be in telH

so i'm actually looking to parse the 7 numbers out of the string and set it to the string telH, this is what i have
Code:
Match mymatch = Regex.Match(telH, @"\d{3}[^0-9]*?\d{4}", RegexOptions.None);

     if (mymatch.Success)
     {
     telHP = mymatch.Value.Substring(0, 3);
     telHS = mymatch.Value.Substring(mymatch.Length - 4, 4);
     }
so if i have a string like so:

string telH = " 123 1234 cell"
the regex would yield
telHP = "123"
telHS = "1234"

How can this be accomplished, thanks
 
This does the trick. You can be the judge if it is simpler. I tweaked the regex to pull the numbers out in chunks. Then you just have to parse the collections to get your guys.

Code:
            string telH = " asd833. 0000 cell ";

            string telH2 = " 777 9999 C ";

            string pattern = @"\d+";

            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern);

            System.Text.RegularExpressions.MatchCollection collection1 = regex.Matches(telH);
            string telHP1 = collection1[0].Captures[0].ToString();
            string telHS1 = collection1[1].Captures[0].ToString();
            
            System.Text.RegularExpressions.MatchCollection collection2 = regex.Matches(telH2);
            string telHP2 = collection2[0].Captures[0].ToString();
            string telHS2 = collection2[1].Captures[0].ToString();

----------------------------------------

TWljcm8kb2Z0J3MgIzEgRmFuIQ==
 
Not necessarily superior or inferior, just illustrative of a use of replace.
[tt]
if (Regex.Match(telH, @"^[\s\S]*?(\d{3}).*?(\d{4})[\s\S]*$").Success) {
telHP=Regex.Replace(telH,"$1");
telHS=Regex.Replace(telH,"$2");
}[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top