Take the 2-minute tour ×

How do you match more than one space character in Java regex?

I have a regex I am trying to match. The regex fails when I have two or more space characters.

 public static void main(String[] args) 
            String $pattern = "\\b(fruit)\\s+([^a]+\\w+)\\b"; //Match 'fruit' not followed by a word that begins with 'a'
            String $str = "fruit apple"; //One space character will not be matched
            String $str_fail = "fruit  apple"; //Two space characters will be matched
            System.out.println(preg_match($pattern,$str)); //False (Thats what I want)
            System.out.println(preg_match($pattern,$str_fail)); //True (Regex fail)
    public static boolean preg_match(String $pattern,String $subject)
            Pattern regex = Pattern.compile($pattern);
            Matcher regexMatcher = regex.matcher($subject);
            return regexMatcher.find();
share|improve this question
String $pattern => String pattern in Java standard coding conventions. –  assylias Jun 7 '12 at 14:58
Is that... php syntax in Java code? –  ean5533 Jun 7 '12 at 14:58
Could be that the second space is matched by [^a] (a space is not an 'a') –  erikxiv Jun 7 '12 at 15:00
My question is on the regex \s+ , why is it not working. The php stuff looks that way because I am porting a php app to java. Everything (The above code) compiles in java. –  DeveloperNumberOne Jun 7 '12 at 15:00
Don't port a PHP app to Java, it can't work. Port the functionality, but embrace Java –  Sean Patrick Floyd Jun 7 '12 at 15:01
add comment

1 Answer

up vote 8 down vote accepted

The problem is actually because of backtracking. Your regex:


Says "fruit, followed by one or more spaces, followed by one or more non 'a' characters, followed by one or more 'word' characters". The reason this fails with two spaces is because \s+ matches the first space, but then gives back the second, which then satisfies the [^a]+ (with the second space) and the \s+ portion (with the first).

I think you can fix it by simply using the posessive quantifier instead, which would be \s++. This tells the \s not to give back the second space character. You can find the documentation on Java's quantifiers here.

As an illustration, here are two examples at Rubular:

  1. Using the possessive quantifier on \s (gives expected results, from what you describe)
  2. Your current regex with separate groupings around [^a\]+ and \w+. Notice that the second match group (representing the [^a]+) is capturing a the second space character.
share|improve this answer
Correct analysis and a valid solution. A second possible solution would be to change [^a] to [^a\s]. –  ean5533 Jun 7 '12 at 15:01
@eldarerathis Your solution \\s++ works. –  DeveloperNumberOne Jun 7 '12 at 15:06
add comment

Your Answer


