Zbarcea Christian
Zbarcea Christian

Reputation: 9548

Java regex find symbols in a string

I'm looking for some explanation for Java regex. I have read and tried different tutorials, but my code doesn't want to work.

String myString = "JKAE[JKk]jkhe{kjef}kaejf-aef_a|ef=kjef+kejf\akejf/efj:efa;aef'asd"fd,<ef>";

if( myString.matches(".*[\\[|]|\\{|\\}|-|+|\\\\|;|:|\\'|\\"|<|>|/") ){
   log("something");
   return;
}

Only alphanumeric characters is allowed, inclusive "." [dot] Symbols not allowed: -_=+\|[{]};:'",<>/

Upvotes: 0

Views: 11259

Answers (1)

Bohemian
Bohemian

Reputation: 425073

It's a little hard to tell what you want, so here's two options:

For only alphanumeric and the dot:

if (!myString.matches("[a-zA-Z0-9.]*") {
    // contained an invalid character
}

To disallow the characters you listed:

if (!myString.matches("[^-_=+\\\\|\\[{\\]};:'\",<>/]*") {
    // contained an invalid character
}

Upvotes: 3

Related Questions