tags:

views:

102

answers:

6

I am trying to write a regular expression that will get the last ':' and everything after it. This is my regular expression in C#:

Regex rx5 = new Regex(@"[A-Za-z.][^\s][^:]{1,}$",RegexOptions.Singleline);

it works except it includes the ':' in there. How do I just get everything after the ':' not including the ':'?

+2  A: 

I would use this regular expression:

^(?:[^:]*:)+([^:]*)$

The first match group will then contain the rest after the last :.

Gumbo
+1  A: 

Use a group, and you could also rewrite the regex to something simpler:

Regex rx5 = new Regex(":([^:]*)$",RegexOptions.Singleline);

Then you have:

Match ma = rx5.Match("test:1:2:3");
if (ma.Success)
{
    // your content is in ma.Groups[1].Value
}
Lasse V. Karlsen
+8  A: 

By not using a regex, but String.LastIndexOf and Substring()

Treb
+1  A: 

Or you could just use the following pattern:

Regex rx5 = new Regex("[^:]+)$",RegexOptions.Singleline);
TruthStands
+1, but drop the useless Singleline modifier. In fact, it doesn't belong in any of the other replies either.
Alan Moore
A: 

Use a lookbehind to not include the last ":"

 Regex rx5 = new Regex("(?<=:)([^:]*)$",RegexOptions.Singleline);
patjbs
+1  A: 

You are better off doing str.Substring(str.LastIndexOf(':')+1).

Regular expressions are powerful but don't try to use them when there is a simpler approach.

Stephan