1

I have a string as following 2 - 5 now I want to get the number 5 with Regex C# (I'm new to Regex), could you suggest me an idea? Thanks

2
  • why not use string.Split('-') and then get the second element from the array ? Commented Apr 14, 2014 at 14:29
  • Why do you need regex? Commented Apr 14, 2014 at 14:29

4 Answers 4

2

You can use String.Split method simply:

int number = int.Parse("2 - 5".Split('-', ' ').Last());

This will work if there is no space after the last number.If that is the case then:

 int number = int.Parse("2 - 5  ".Split('-', ' ')
              .Last(x => x.Any() && x.All(char.IsDigit)));
Sign up to request clarification or add additional context in comments.

Comments

1

Very simply as follows:

'\s-\s(\d)'

and extract first matching group

Comments

1

@SShashank has the right of it, but I thought I'd supply some code, since you mentioned you were new to Regex:

string s = "something 2-5 another";
Regex rx = new Regex(@"-(\d)");
if (rx.IsMatch(s))
{
    Match m = rx.Match(s);
    System.Console.WriteLine("First match: " + m.Groups[1].Value);
}

Groups[0] is the entire match and Groups[1] is the first matched group (stuff in parens).

2 Comments

Thanks @James Jensen, could you please suggest me the idea when I have to take the string on the URL such as www.the-world-is-awesome.com I want to take the is-awesome in the URL and I tried with this pattern : @ "http: //www.the-world-(?<host>[A-Z-.]+).com" but it warns me an error in the pattern.
@user3520221: You need to escape the dashes and other metacharacters in the pattern if you want to match them verbatim. Also, you need to make sure that the named match has the correct pattern as well. For example, http://www\.the\-world\-(?<host>.+)\.com will match your example in a .NET Regex object and return "is-awesome".
0

If you really want to use regex, you can simply do:

string text = "2 - 5";

string found = Regex.Match(text, @"\d+", RegexOptions.RightToLeft).Value;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.