Jérémy
Jérémy

Reputation: 429

How to write valid regex groups?

I try to write regex in order to validate that :

I have write a regex (^[^a-z]+$)(^[^ ]+$) but when i test it, SFSFSDis incorrect.

How can i do that ?

Thanks ! :)

Upvotes: 1

Views: 89

Answers (3)

Tuan Bao
Tuan Bao

Reputation: 266

I use the regex to validate that: /^(?!^ +$)([^a-z]+)$/

Explanation

  • ^ matches the position before the first character in the string.
  • (?!^ +$) negative lookahead, that matches if the string not only whitespace.
  • ([^a-z]+) matches all characters except lowercase characters.
  • $ matches the right after character position of the string.

Upvotes: 0

Hülya
Hülya

Reputation: 3433

You can also use the regex (^(?!\\s+$)[^a-z]+)

  • (?!\\s+$) part checks if the regex does not contain only whitespaces till the end
  • [^a-z]+ then check for the lowercase characters

Tested with a few samples:

List<String> wordList = Arrays.asList("   ", "SFSFSD", "as DDdkj", "AB CD", "    k", "l  l");
String regex = "(^(?!\\s+$)[^a-z]+)";
for(String word : wordList) {
    if(word.matches(regex)) {
        System.out.println(word + " :valid");
    } else {
        System.out.println(word + " :not valid");
    }
}
    

Output:

    :not valid
SFSFSD :valid
as DDdkj :not valid
AB CD :valid
     k :not valid
l    l :not valid

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522626

You could use:

^[^a-z]*[^a-z\s][^a-z]*$

This would assert that there be at least one non whitespace, non lowercase letter, character, with the remaining being either whitespace or non lowercase.

Upvotes: 0

Related Questions