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

Community
  • 1
  • 1
Adeeb Cheulkar
  • 1,128
  • 2
  • 10
  • 22

3 Answers3

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]*))
dryairship
  • 6,022
  • 4
  • 28
  • 54
1

You could do

if ("Apple Juice".matches("\\w+ \\w+")) {
 .......
Reimeus
  • 158,255
  • 15
  • 216
  • 276
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.

dimplex
  • 494
  • 5
  • 9