简体   繁体   中英

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:

  • "Flat 1, Asker Horse Sports", -- get string after "," result: "Asker Horse Sports"
  • "9 Walkers Barn" -- get string after "9" result: Walkers Barn

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.

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;

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM