0

I'm looking for a regex in Java, java.util.regex, to accept only letters , -, and . and a range of Unicode characters such as umlauts, eszett, diacritic and other valid letters from European languages. What I don't want is numbers, spaces like “ ” or “ Tom”, or special characters like !”£$% etc.

So far I'm finding it very confusing.

I started with this

[A-Za-z.\\s\\-\\.\\W]+$

And ended up with this:

[A-Za-z.\\s\\-\\.\\D[^!\"£$%\\^&*:;@#~,/?]]+$

Using the cavat to say none of the inner square brackets, according to the documentation

Anyone have any suggestions for a new regex or reasons why the above isn't working?

2
  • Are you getting an error message, or is it just not matching. In both cases, give us more information what exactly happens. Commented Oct 31, 2012 at 13:16
  • One problem might be that you use \\D. Use \\d inside the negated character class instead. Also, you should add ^ to the beginning. Otherwise your regex will match if only the last character of your string is one of the allowed ones. Commented Oct 31, 2012 at 13:21

2 Answers 2

1

For my answer, I want to use a simpler regex similar to yours: [A-Z[^!]]+, which means "At least once: (a character from A to Z) or (a character that is not '!').
Note that "not '!'" already includes A to Z. So everything in the outer character group([A-Z...) is pointless.

Try [\p{Alpha}'-.]+ and compile the regex with the Pattern.UNICODE_CHARACTER_CLASS flag.

Sign up to request clarification or add additional context in comments.

Comments

0

Use: (?=.*[@#$%&\s]) - Return true when atleast one special character (from set) and also if username contain space.

you can add more special character as per your requirment. For Example:

String str = "k$shor";
String regex = "(?=.*[@#$%&\\s])";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.find()); => gives true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.