简体   繁体   中英

Is there any specific way to check if there's only one letter in regex?

I wanted to find a regex pattern that checks if there's one letter in between the space.

For example: John A Doe I want to capture only John Doe (without A) but there's 50/50 chance that the data will not contain middle initials.

I made this pattern ([Az]* [Az] [Az]*|[Az]* [Az]*) but it captures also the middle one.

I'm sorry for the vague title cause I'm really confused rn.

Edit: I forgot about the [Az] captures upto 122 in ascii table. I replaced it with \w as well.

Perhaps code like:

var m = Regex.Match(input, @"(?<f>[a-z]+)( [a-z])? (?<l>[a-z]+)", RegexOptions.IgnoreCase);

Console.WriteLine(m.Groups["f"].Value);
Console.WriteLine(m.Groups["l"].Value);

You'll need to capture the first and last names separately and stick them back together later

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