0

Hi I have tried the following and it seems not working. Can you explain me why ?

public class Solution  {
public static void main(String[] args) {
    String abc =" ";
    String regx = ".*[^\\s].*";
    if (abc.matches(regx)) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }

}

}

I have tried another case

public class Solution  {
public static void main(String[] args) {
    String abc =" ";
    String regx = ".*[^\\s].*";
    Pattern r = Pattern.compile(regx);
    Matcher m = r.matcher(abc);
    if (m.find()) {
        System.out.println(true);
    } else {
        System.out.println(false);
    }

}

I have given abc = " ",abc = " ". in all the case i am getting false as output.I dont understand why ?

Thanks.

  • 2
    Why a regular expression? just trim it and check if the length is greater then 0. Additionally your false is correct, you check if there is any non `whitespace` character, which is not the case, so the `false` is correct. – SomeJavaGuy Jul 14 '16 at 06:20
  • Do you _really_ mean "finding strings containing only white space"? Your code would seem to indicate not, but it's not possible to tell what you oare really trying to do. – Jim Garrison Jul 14 '16 at 06:21
  • 1
    Do either what Kevin says (preferable solution) or just use `matches("\\s+")` – TheLostMind Jul 14 '16 at 06:21
  • Thanks. I have confused with the expression. Thanks a lot for giving a way :-) – Arjun Nagathankandy Jul 14 '16 at 06:25
  • 1
    Well, trim space and then check length will work fine if you expect only spaces in the string. But if there are also tabs and linefeeds then `matches("^\\s+$")` will check if it's nothing but whitespace in the string. Or just `matches("^[ ]+$")` to check if it only contains spaces. – LukStorms Jul 14 '16 at 06:52

0 Answers0