dban
dban

Reputation:

Regular expression to get last colon in string and everything after it

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 ':'?

Upvotes: 2

Views: 2668

Answers (6)

Stephan
Stephan

Reputation: 5488

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.

Upvotes: 2

patjbs
patjbs

Reputation: 4772

Use a lookbehind to not include the last ":"

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

Upvotes: 1

TruthStands
TruthStands

Reputation: 93

Or you could just use the following pattern:

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

Upvotes: 1

Treb
Treb

Reputation: 20289

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

Upvotes: 11

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391496

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
}

Upvotes: 2

Gumbo
Gumbo

Reputation: 655499

I would use this regular expression:

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

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

Upvotes: 2

Related Questions