Saad
Saad

Reputation: 907

Regex to find a string containing more than a single whitespace with no leading/trailing whitespace

Currently i have

    Pattern p = Pattern.compile("\s");
    boolean invalidChar = p.matcher(text).find();

I want it to return true only when i have more than a single whitespace. Also there should not be any whitespace in the beginning or ending of string.

So some valid/invalid text would be

12 34 56 = valid

ab-34 56 = valid

ab    34 = invalid

     12 34 53 = invalid

Upvotes: 2

Views: 106

Answers (5)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89565

You can use this pattern:

Pattern p = Pattern.compile("(?<!\\S)(?!\\S)");
Matcher m = p.matcher(text);

boolean invalidChar = m.find();

or boolean isValid = !m.find(), as you want.

Where (?<!\\S) means "not preceded by a non-whitespace" (that includes a preceding whitespace or the start of the string) and (?!\\S) "not followed by a non-whitespace" (that includes a following whitespace or the end of the string).

These two lookarounds describe all possible cases:

  • successive white-spaces (matches the position between the first two white-spaces)
  • white-space at the beginning or at the end
  • empty string

Upvotes: 1

Bruno Carletti
Bruno Carletti

Reputation: 273

Try this:

(^\s{1,}|\s{2,}|\s$)

Final:

Pattern p = Pattern.compile("(^\s{1,}|\s{2,}|\s$)");

Upvotes: 3

Josh Withee
Josh Withee

Reputation: 11336

Try this:

boolean invalidChar = text.matches("\\S(?!.*\\s\\s).*\\S");

Explanation:

\\S - the match begins with a non-whitespace character

(?!.*\\s\\s) - negative lookahead assertion to ensure there are no instances of two whitespace characters next to each other

.* - matches 0 or more of any character

\\S - the match ends with a non-whitespace character

Note: the matches("regex") method returns true only if the regex matches the entire text string.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627020

Since there can't be whitespace at the start and end of the string, and there cannot be two or more consecutive whitespaces inside, you may use

boolean isValid = s.matches("\\S+(?:\\s\\S+)*"); 

This expression will match the following:

  • ^ (implicit in matches that anchors the match by default, i.e. the whole string must match the regex pattern) - the start of the string
  • \S+ - 1 or more chars other than whitespaces
  • (?:\s\S+)* - zero or more sequences of:
    • \s - a single whitespace
    • \S+ - 1 or more chars other than whitespaces
  • $ (implicit in matches) - the end of the string.

See the regex demo.

Upvotes: 1

zlakad
zlakad

Reputation: 1384

Without regex..

public class Answ {

    public static boolean isValid(String s) {
        return !s.contains("  "); //two white spaces
    }

    public static void main(String[] args) {
        String st1 = "12 34 56";

        System.out.println(isValid(st1));
    }
}

Upvotes: 3

Related Questions