Home > Net >  Regex NotBlank and doesnt contains <
Regex NotBlank and doesnt contains <

Time:10-08

I try to create a regex for a String which is NotBlank and cannot contain "<". My question is what Im doing wrong thank you.

"(\\A(?!\\s*\\Z))|([^<] )"

Edit Maybe this way how to combine this regex

^[^<] $

with this regex

\\A(?!\\s*\\Z). 

CodePudding user response:

With regex, you can use

\A(?!\s \z)[^<] \z
(?U)\A(?!\s \z)[^<] \z

The (?U) is only necessary when you expect any Unicode chars in the input.

In Java, when used with matches, the anchors on both ends are implicit:

text.matches("(?U)(?!\\s \\z)[^<] ")

The regex in matches is executed once and requires the full string match. Here, it matches

  • \A - (implicit in matches) - start of string
  • (?U) - Pattern.UNICODE_CHARACTER_CLASS option enabled so that \s could match any Unicode whitespaces
  • (?!\\s \\z) - until the very end of string, there should be no one or more whitespaces
  • [^<] - one or more chars other than <
  • \z - (implicit in matches) - end of string.

See the Java test:

String texts[]  = {"Abc <<", "     ", "", "abc 123"};
Pattern p = Pattern.compile("(?U)(?!\\s \\z)[^<] ");
for(String text : texts)
{
    Matcher m = p.matcher(text);
    System.out.println("'"   text   "' => "   m.matches());
}

Output:

'Abc <<' => false
'     ' => false
'' => false
'abc 123' => true

See an online regex test (modified to fit the single multiline string demo environment so as not to cross over line boundaries.)

CodePudding user response:

You can try to use this regex:

[^<\s] 

Any char that is not "<", for 1 or more times.

Here is the example to test it: https://regex101.com/r/9ptt15/2

However, you can try to solve it without a regular expression:

boolean isValid = s != null && !s.isEmpty() && s.indexOf(" ") == -1 && s.indexOf("<") == -1;
  • Related