Cass
Cass

Reputation: 129

Regex to detect consecutive characters

Hope someone can help me with a regular expression to validate names. The criteria are that the string must be between 1 and 30 characters in length and will allow the following: uppercase alpha, lowercase alpha, space, apostrophe, full stop (or period) and hyphen.

I’ve got a regex that will do this, but the complication is that the "special" characters (space, apostrophe, full stop, hyphen) may not be consecutive. So you could not have this: "Smithers-'Jones" (hyphen followed by apostrophe), or this: "Smithers –Jones" (space followed by hyphen), or this "O''Reilly" (consecutive apostrophes).

From what I’ve read so far, I think I need to use back-references in some way, but I haven't managed to get anything working yet. I've seen examples that detect repeating characters, but this is not quite the same.

Any help would be appreciated.

Upvotes: 5

Views: 18435

Answers (1)

anubhava
anubhava

Reputation: 785068

This regex should work:

^(?!.*?[ '.-]{2})[A-Za-z0-9 '.-]{1,30}$

Working Demo: http://regex101.com/r/pJ3hJ9

Upvotes: 10

Related Questions