0

Regular expression mentioned below is used to validate a user input in Java.

username.matches("^\\p{L}+[\\p{L}\\p{Z}.']+")

The regular expression is working for more than one character input, but fails for single character input.

As '+' denotes one and more than one characters, I confused how to support one character input as valid input.

3 Answers 3

2

That's because both parts in your regex are requiring at least one character each (see the + almost at the end of the regex). If you want that part to be optional, it should be * instead.

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

Comments

1

The regex you have will match 2 or more symbols. The reason is, this is symbol one (or more):

\\p{L}+

And this is symbol 2 (or more):

[\\p{L}\\p{Z}.']+

Most likely you want the last part to be "0 or more", like this:

"^\\p{L}+[\\p{L}\\p{Z}.']*"

1 Comment

My bad! I missed the second '+' sign
1

Your regex requires a minimum of 2 characters.

"^\p{L}+" - minimum of 1
"[\p{L}\p{Z}.']+" - minimum of 1

The "+" does denote one or more characters.

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.