Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

negating java regex

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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].*")

>Solution :

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");

}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading