Skip to content
Advertisement

How to validate spaces between two words using regex in a string [closed]

I am trying to validate string to accept spaces between two words (in the middle).

I want a regex that will accept “hello world”.

I tried using [p{IsAlphabetic}p{Digit}-_]{0,255}.

Thanks in advance!

Advertisement

Answer

You need to use \w+\s+\w+ if you want to match two string separated by space(s).

public class Main {
    public static void main(String[] args) {
        String[] testStrs = { "Hello", "Hello World", "123 456", "123456","Hello world good" };
        for (String s : testStrs) {
            System.out.println(s + " => " + s.matches("\w+\s+\w+"));
        }
    }
}

Output:

Hello => false
Hello World => true
123 456 => true
123456 => false
Hello world good => false
Advertisement