0

A validation to be developed for a JavaFX text field where single whitespace is allowed but more than one whitespace is not be allowed.

For example, "Apple Juice" -- correct "Apple Juice" -- incorrect should be restricted

if (title.matches("[a-zA-Z0-9 ]+"))

Found couple of links but not meeting my requirement. I believe that it is more of a logical tweak.

Whitespace Matching Regex - Java

Regex allowing a space character in Java

3 Answers 3

2

You can do:

if (title.matches([a-zA-z]+[ ][a-zA-Z]+))
  • The first [a-zA-z]+ checks for any characters before the space.
  • The [ ] checks for exactly one space.
  • The second [a-zA-z]+ checks for any characters after the space.


Note: This will match only if the space is present in between the string. If you want to match strings like Abcd<space> or <space>Abcd, (I used <spcace> as SO does not allow two spaces to be present simultaneously) then you can replace the +s with *s., i.e.,

if (title.matches([a-zA-z]*[ ][a-zA-Z]*))
Sign up to request clarification or add additional context in comments.

Comments

1

You'd better find more than a single whitespace and negate the result:

if(!title.trim().matches("\s{2,}"))

, see java.util.regex.Pattern javadoc for the syntax. The string is first trimmed, so you don't need to check for non-whitespace characters. If you don't do the trim() operation, leading and trailing whitespace will also be considered.

Comments

1

You could do

if ("Apple Juice".matches("\\w+ \\w+")) {
 .......

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.