Alin Golumbeanu
Alin Golumbeanu

Reputation: 599

Get string after the last comma or the last number using Regex in C#

How can I get the string after the last comma or last number using regex for this examples:

I need that regex to support both cases or to different regex rules, each / case.

I tried /,[^,]*$/ and (.*),[^,]*$ to get the strings after the last comma but no luck.

Upvotes: 3

Views: 521

Answers (2)

The fourth bird
The fourth bird

Reputation: 163372

You were on the right track the capture group in (.*),[^,]*$, but the group should be the part that you are looking for.

If there has to be a comma or digit present, you could match until the last occurrence of either of them, and capture what follows in the capturing group.

^.*[\d,]\s*(.+)$
  • ^ Start of string
  • .* Match any char except a newline 0+ times
  • [\d,] Match either , or a digit
  • \s* Match 0+ whitespace chars
  • (.+) Capture group 1, match any char except a newline 1+ times
  • $ End of string

.NET regex demo | C# demo

enter image description here

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626950

You can use

[^,\d\s][^,\d]*$

See the regex demo (and a .NET regex demo).

Details

  • [^,\d\s] - any char but a comma, digit and whitespace
  • [^,\d]* - any char but a comma and digit
  • $ - end of string.

In C#, you may also tell the regex engine to search for the match from the end of the string with the RegexOptions.RightToLeft option (to make regex matching more efficient. although it might not be necessary in this case if the input strings are short):

var output = Regex.Match(text, @"[^,\d\s][^,\d]*$", RegexOptions.RightToLeft)?.Value;

Upvotes: 3

Related Questions