简体   繁体   中英

How to find last alphabet in a string using c# .net

I want to find out the last alphabet in a string in c# .net. For instance, I have 1234B0097D576676 and I need to find D . Same as in 0103D0001Y000001 , the result should be Y .

To do this there is a function in PHP preg_match('/[^a-zA-Z]+$/', $scanned_code, $match); . This will return the last occured character in the string. How can we do the same in c# .net? Thanks in advance.

i would choose a linq soultion

string chars = "1234B0097D576676";
char Result = chars.LastOrDefault(x => Char.IsLetter(x));

You can use a positive lookahead in the regex [az](?=[^az]*$) with Ignorecase option to get that last letter.

var txt1 = "0103D0001Y000001";
var regex1 = new Regex(@"[a-z](?=[^a-z]*$)", RegexOptions.IgnoreCase  | RegexOptions.CultureInvariant);
var c1 = regex1.Matches(txt1).Cast<Match>().Select(d => d.Value.Trim()).ToList();

Output:

在此处输入图片说明

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