SCENARIO :
Pattern whitespace = Pattern.compile("^\\s");
matcher = whitespace.matcher(" WhiteSpace");
Pattern whitespace2 = Pattern.compile("^\\s\\s");
matcher2 = whitespace2.matcher(" WhiteSpace");
I am trying to get whitespaces at the beginning of a line. I want to get exact number of white spaces matcher true. My string is " WhiteSpace".
Problem is both matcher and matcher2 work on this string.
The thing I want is:
A pattern that only get 1 white space, but this pattern should not work
for 2 white space string. In the scenario below both matcher.find() and matcher2.find() are true. But matcher.find() should be false, matcher2.find() should be true.
I want matcher to be true for " WhiteSpace", false for " WhiteSpace" (two spaces)
I want matcher2 to be true for :" WhiteSpace".
The thing I want to do is;
I have a string " two whitespaces".
Below both if statements are true. matcher should be false.
matcher2 should be true.
Pattern whitespace = Pattern.compile("^\\s");
matcher = whitespace.matcher(" two whitespaces");
Pattern whitespace2 = Pattern.compile("^\\s\\s");
matcher2 = whitespace2.matcher(" two whitespaces");
if(matcher.find()==true){
//XXXXXXXXXXX
} else if(matcher2.find()==true){
//YYYYYYYYYYY
}
2 Answers 2
If you want to ensure that after one whitespace there is no another whitespace, but you don't actually want to include that second character which you will test in match (regardless if it was whitespace or not), you can use negative lookahead mechanism (?!..).
So pattern which can match only whitespace at start of line if it doesn't have another whitespace after it may look like
Pattern whitespace = Pattern.compile("^\\s(?!\\s)");
This can be adapted for any number by spaces
Pattern whitespace = Pattern.compile("^\\s{3}(?!\\s)");
Comments
A pattern may be an overkill here*. Use Character.isWhitespace and get a simpler code:
String in = " your input here";
int wsPrefix=0;
for ( ; wsPrefix < in.length() && Character.isWhitespace(in.charAt(wsPrefix)) ;
wsPrefix++ ) {}
System.out.println("wsPrefix = " + wsPrefix);
* For it is said:
"Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. -- Jaimie Zawinski, 1997