Chris
Chris

Reputation: 2284

Check if String contains tab plus any non white space character

I would like to check if a given String starts with a given amount of tabs + any character BUT white-space-character. This is what I tried but it is not working:

public static boolean hasCorrectIndentation(String line, String tabs) {
    return line.matches(tabs + "\\S+"); 
}

Example 1:

hasCorrectIndentation("public class inputFile {", ""))

OUTPUT: false

Example 2:

hasCorrectIndentation("    public class inputFile {", "\t"))

OUTPUT: false

Upvotes: 0

Views: 1852

Answers (1)

Nick
Nick

Reputation: 147196

Your issue is that String.matches (which is equivalent to Pattern.matches) effectively adds start and end of string anchors to your regex. From the documentation for Matcher:

The matches method attempts to match the entire input sequence against the pattern.

So

line.matches(tabs + "\\S+")

is equivalent to

line.matches("^" + tabs + "\\S+$")

and since you have spaces in the rest of the line (after public) the match fails. You need to allow for spaces after the first non-space character, using something like:

line.matches(tabs + "\\S.*")

Upvotes: 1

Related Questions