Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to detect consecutive characters

Tags:

regex

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.

like image 832
Cass Avatar asked Feb 28 '14 14:02

Cass


People also ask

What is consecutive identical characters?

Consecutive means one after another. And identical means the exact same. So this means that. There are 3 exact same characters that repeated. “AAA”

How do I match a specific character in regex?

Match any specific character in a setUse square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.


1 Answers

This regex should work:

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

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

like image 57
anubhava Avatar answered Oct 05 '22 07:10

anubhava