Xeshan J
Xeshan J

Reputation: 372

Name validation with special conditions using regex

I want to validate the Name in Java that will allow following special characters for single time {,-.'}. I am able to achieve with the Expression that will allow user to enter only such special characters in a string. But I am not able to figure it out how to add restrictions where users cannot add these characters more then one time. I tried to achieve it using quantifiers but remain unsuccessful. I have done the following code yet!

Pattern validator = Pattern.compile("^[a-zA-Z+\\.+\\-+\\'+\\,]+$");

Upvotes: 1

Views: 281

Answers (2)

anubhava
anubhava

Reputation: 785971

You can use lookahead assertion in your regex:

Pattern validator = Pattern.compile(
  "^(?!(?:.*?\\.){2})(?!(?:.*?'){2})(?!(?:.*?,){2})(?!(?:.*?-){2})[a-zA-Z .',-]+$");

(?!(?:.*?[.',-]){2}) is a negative lookahead that means don't allow more than 1 of those characters in character class.

RegEx Demo

Upvotes: 1

Jon Thoms
Jon Thoms

Reputation: 10787

I think that you can just take into account names where such characters would only happen once. Names like "Jonathan's", "Thoms-Damm", "Thoms,Jon", "jonathan.thoms". In practice for names, I don't think that such special characters would occur at the edges of the string. As such, you can probably get away with a regex like:

Pattern validator = Pattern.compile("^[a-zA-Z]+(?:[-',\.][a-zA-Z]+)?$");

This regex should match a regular ASCII name followed optionally by a single "special" character with another name after it.

Upvotes: 0

Related Questions