Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 283
  • Last Modified:

method to determine if String contains non-alphanumeric

I need a method that determines if a String contains non-alphanumeric characters or not.
Surely this exists somewhere, but I'm not finding it.
0
allelopath
Asked:
allelopath
  • 5
  • 5
2 Solutions
 
CEHJCommented:
boolean containsNonAlpha = !s.matches("\\w+");
0
 
CEHJCommented:
If you want to exclude the underscore, do

boolean containsNonAlpha = !s.matches("[A-Za-z0-9]+");
0
 
objectsCommented:
use commons langs (it has that and many more), or create your own method (using a simple loop).
You can do it using regexp but its unnecessarily slow and will use memory unnecessarily, so is considered bad practice.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
CEHJCommented:
Unless you have a very long string, you shouldn't worry about memory or performance. If you do, you probably shouldn't be using Java in the first place, particularly in the former regard ;-)
0
 
allelopathAuthor Commented:
The String in question is 10 characters long.
0
 
CEHJCommented:
;-)
0
 
objectsCommented:
> The String in question is 10 characters long.

The length of the string is in fact irrelevant, though it does make the loop faster (regex will still not get much better though due to overhead involved)
0
 
objectsCommented:
> you shouldn't worry about memory or performance.

most common cause of issues with Java applications is from new developers *not* worrying about memory and performance, and then trying to track down why there app runs so slowly and keeps requiring more memory :)
0
 
objectsCommented:
There are libraries to do this sort of thing as I mentioned above, and they do *not* use regexp for the reasons I have stated.

     public static boolean isAlphanumeric(String str) {
         if (str == null) {
             return false;
         }
         int sz = str.length();
         for (int i = 0; i < sz; i++) {
             if (Character.isLetterOrDigit(str.charAt(i)) == false) {
                 return false;
             }
         }
         return true;
     }
0
 
objectsCommented:
Add that to a Utils class (or whatever u want to call it) and use it with:

boolean alphanumeric = Utils.isAlphanumeric(mystring);
0
 
CEHJCommented:
:-)
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 5
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now