Home > Software design >  negating java regex
negating java regex

Time:01-15

I'm using these lines to check if a String does not contain only "special" characters:

String regex = "^[^a-zA-Z0-9]*$";

if(!someinput.matches(regex)){
    System.out.println("your input isn't made of only special characters");
}

But I want the regex to not necessitate the "!" negation before it, so as to make it self-sufficient.

I've tried the look ahead "^(?![^a-zA-Z0-9]*)$" , but It doesn't work. Why doesn't it work and what should I do?

EDIT: SOLVED BY COMMENTS

So, I was looking for a regex that identifies any string containing at least one alphanumeric character.

My first and second try both looked at it from a "negation" point of view: I was going at the problem by trying to find a regex that identifies all those strings whose characters aren't special.

But the cleanest solution was to find all those strings which contain at least one alphanumeric character.

So I needed a semantic inversion?

Anyway I like this solution proposed by @Bohemian

matches(".*[A-Za-z0-9].*")

CodePudding user response:

Try this:

String regex = ".*[a-zA-Z0-9].*"; // a letter/digit is somewhere in the string 

if (!someinput.matches(regex)) {
    System.out.println("your input isn't made of only special characters");

}

CodePudding user response:

If you want to match

a string containing at least one alphanumeric char

then to use pattern.asPredicate() may be more readable:

Pattern pattern = Pattern.compile("[a-zA-Z0-9]");

String notOnlySpecial = "#####%$#!#s";

if(pattern.asPredicate().test(notOnlySpecial)){
    System.out.println("your input isn't made of only special characters");
}
  • Related