0

I am trying to match only the phrase that is positioned at the end of the sentence, just after a comma. I could split the string by commas and grab the last index but how can I do the same with regex that finds 1 or more words going form right to left and ends at first comma?

string str = "some string, number 555 more strings, final string";
var match = new Regex(@"(?=,\s).*", RegexOptions.RightToLeft).Match(str).Value;
Console.WriteLine(match); // , number 555 more strings, final string

In snippet above I tried to match final string only. If regex101 had the right-to-left feature I would tinker with it as usually until I found the proper syntax.

I tried to use both lookahead and lookbehind but I find it very confusing when going right to left.

miran80
  • 945
  • 7
  • 22
  • 1
    You forget that `.*` is greedy, use lazy one and add `$`, and use a *lookbehind*, not a lookahead, i.e. the overall regex will look like `(?<=,\s).*?$` – Wiktor Stribiżew Apr 29 '20 at 17:54
  • No need for lazy version if he uses a character class that excludes the comma. No need for lookbehind if he starts the match WITH a comma but uses a capturing group only on what follows it. –  Apr 29 '20 at 17:56

1 Answers1

0

Use the $ end-of-string anchor:

Regex(@"[^,]*$", ...
  • This worked and gave me `, final string`, changing it to `@"([^,]*)$"` got rid of the comma and I could `Trimm()` it from here on but how do I get rid of the leading space with regex? – miran80 Apr 29 '20 at 18:01
  • 1
    That would be `Regex (@",\s+([^,]*)$").Match (str).[1].Value` The [1] selecting the first capturing group. –  Apr 29 '20 at 18:04
  • It is `Groups[ 1 ]`, my bad. –  Apr 29 '20 at 18:10