I'm trying to create a regex that can be used to verify if a string contains only initials, then followed by commas if there is more than one initial.
This is the best I've managed to do: "^([A-Za-z],[A-Za-z],[A-Za-z])$"
by replacing all spaces with ""
.
An example of an allowed string would be a, b, c, d, f, g
while one that wouldn't pass would be a, b, c, df, e
This only works for exactly 3 initials, so I was wondering how I could get it to work with more or less initials while also not letting any outliers through.
Edit: ^([A-Za-z],([A-Za-z],)*[A-Za-z])$"
seems to work quite well, but how would I change this code to work for just 1 character (since I need the last character, which usually doesn't have a comma following it)
Try the following pattern:
^[A-Za-z](?:,\s+[A-Za-z])*$
This matches a single character/initial, then followed by zero or more commas followed by whitespace and another initial.
您可以使用此正则表达式来匹配首字母,它不查看逗号,只查看首字母并匹配多个找到的:
(?:[a-zA-Z][a-zA-Z])
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.