RegEx 101 exercise I9-count the number of matches

Source: Internet
Author: User
After a long break, Eric is back, and continue his awesome RegEx 101 exercise series, in this exercise, the question Eric asks is:
Bytes -------------------------------------------------------------------------------------------------

Given a string like:

#4 6 #7 #45 #43 #65 56 2 #4345 #23

 

Count how many numbers there are in this string

Bytes --------------------------------------------------------------------------------------------------
I have three simple solutions to this problem.
Solution #1: RegEx = new RegEx (@ "\ D +", regexoptions. ignorecase );
String inputstring = @ "#4 6 #7 #45 #43 #65 56 2 #4345 #23 ";
Int32 COUNT = 0;
RegEx. Replace (inputstring, delegate (match)
{
Count ++;
Return string. empty;
});

Console. writeline (count );

Solution #2: RegEx = new RegEx (@ "\ D +", regexoptions. ignorecase );
String inputstring = @ "#4 6 #7 #45 #43 #65 56 2 #4345 #23 ";
Matchcollection matches = RegEx. Matches (inputstring );
Console. writeline (matches. Count );

Solution #3: RegEx = new RegEx (@ "[# \ s] +", regexoptions. ignorecase );
String inputstring = @ "#4 6 #7 #45 #43 #65 56 2 #4345 #23 ";
String [] values = RegEx. Split (inputstring );
Console. writeline (values. Length-1 );

Side note: For all of you who are interested in regluar expressions, and want to be more proficient at it, I encourage you to actively participant ipate in Eric Gunnerson's RegEx exercises, at the end of day, you will find that you benefit a lot in that process.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.