Regex check for name Initials

linus_hologram :

I am trying to create a regex that checks if one or more middle-name initials have the following stucture:

INITIAL.[BLANK]INITIAL.[BLANK]INITIAL.

There can be multiple Initials as long as they are followed by a dot (.) - blank spaces are only allowed between two initials (e.g. L. B.)

It should not be possible to have a space after an initial if there's no other initial following.

At the moment, I have the following Regex which doesn't work perfectly as of now:

([A-Z]\. (?=[A-Z]|$))+

Using regex101, this is an example: regex output

As you can see, it still matches the string even though there's a blank space at the end, without having another Initial following.

I am not sure why this is happening. I am just learning regex and would be glad if anyone could provide me with a solution to my problem :)

l_l_l_l_l_l_l_l :

The error you're seeing is because at the last step, your expression reads in [A-Z]\. looks ahead for $ (and finds it). I would express the pattern this way: (?:[A-Z]\. )*[A-Z]\.$. Treat the last initial specially because it does not have a final space.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=390419&siteId=1