daveomcd
daveomcd

Reputation: 6555

How can I construct a regular expression to account for non-consecutive characters?

I'm currently using this regex for my names \A^[a-zA-Z'.,\s-]*\z; however, I don't want there to be any consecutive characters for a apostrophe, period, comma, whitespace, or hyphen. How can I do this?

Upvotes: 0

Views: 55

Answers (2)

user4227915
user4227915

Reputation:

The significant part would be (?:[a-zA-Z]|['.,\s-](?!['.,\s-])).

Meaning:

(?:
    [a-zA-Z]         # letters
|                    # or
    ['.,\s-]         # any of these
    (?!['.,\s-])     # but in front can not be another of these
)

But, in this case:

Guedes, Washington
------^^----------

Would invalidate the name, so maybe you want remove \s from the negative look-ahead.

Hope it helps.

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230481

How about this (string of letters, potentially ending with one of those terminator chars)

\A^[a-zA-Z]*['.,\s-]?\z

Upvotes: 1

Related Questions