简体   繁体   English

在 C# 中使用 Regex 获取最后一个逗号或最后一个数字之后的字符串

[英]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" "Flat 1, Asker Horse Sports", -- 在 "," 后得到字符串结果: "Asker Horse Sports"
  • "9 Walkers Barn" -- get string after "9" result: Walkers Barn "9 Walkers Barn" -- 在 "9" 结果后得到字符串: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 ).请参阅正则表达式演示(和.NET 正则表达式演示)。

Details细节

  • [^,\\d\\s] - any char but a comma, digit and whitespace [^,\\d\\s] - 除了逗号、数字和空格之外的任何字符
  • [^,\\d]* - any char but a comma and digit [^,\\d]* - 除了逗号和数字以外的任何字符
  • $ - 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):在 C# 中,您还可以使用RegexOptions.RightToLeft选项告诉正则表达式引擎从字符串末尾搜索匹配项(以使正则表达式匹配更高效。尽管在这种情况下,如果输入字符串很短,则可能没有必要) ):

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 .*匹配除换行符以外的任何字符 0+ 次
  • [\\d,] Match either , or a digit [\\d,]匹配,或数字
  • \\s* Match 0+ whitespace chars \\s*匹配 0+ 个空白字符
  • (.+) Capture group 1 , match any char except a newline 1+ times (.+)捕获组 1 ,匹配除换行符以外的任何字符 1+ 次
  • $ End of string $字符串结尾

.NET regex demo | .NET 正则表达式演示| C# demo C# 演示

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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