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
-
why not use string.Split('-') and then get the second element from the array ?Habib– Habib2014-04-14 14:29:47 +00:00Commented Apr 14, 2014 at 14:29
-
Why do you need regex?anubhava– anubhava2014-04-14 14:29:56 +00:00Commented Apr 14, 2014 at 14:29
Add a comment
|
4 Answers
@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
TrangZinita
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.
James Jensen
@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".