Java, make sure the string contains only alphanumeric, spaces and dashes

In Java, I need to make sure that the string contains only alphanumeric , space and dash characters.

I found the org.apache.commons.lang.StringUtils class and the almost adequate isAlphanumericSpace(String) method ... but I also need to include a dash.

What is the best way to do this? I do not want to use regular expressions.

+4
source share
5 answers

Hum ... just program it yourself using String.chatAt ( int ), it's pretty simple ...

Iterate through all char in a string using a position index, and then compare it using the fact that ASCII characters 0 through 9, a through z and A through Z use sequential codes, so you only need to check that the character x numerically checks one of the conditions:

  • between '0' and '9'
  • between 'a' and 'z'
  • between 'A and' Z '
  • space ''
  • hyphen '-'

Here is an example of the base code (using CharSequence, which allows passing String as well as StringBuilder as arg):

 public boolean isValidChar(CharSequence seq) { int len = seq.length(); for(int i=0;i<len;i++) { char c = seq.charAt(i); // Test for all positive cases if('0'<=c && c<='9') continue; if('a'<=c && c<='z') continue; if('A'<=c && c<='Z') continue; if(c==' ') continue; if(c=='-') continue; // ... insert more positive character tests here // If we get here, we had an invalid char, fail right away return false; } // All seen chars were valid, succeed return true; } 
+6
source

You can use:

 StringUtils.isAlphanumericSpace(string.replace('-', ' ')); 
+10
source

Just iterate over the string using the character class methods in java.lang.Character to check if each character is suitable or not. Apparently this is all that StringUtils methods do, and regular expressions are just a way to get the generalized engine to do the same.

+3
source

You have 1 of 2 options: 1. Make a list of characters that MAY be in the string, then go to check the string to make sure that every IS character in the list. 2. Make a list of characters that CANNOT be in a string, then iterate over the string, making sure that each character is NOT in the list.

Choose any option that will make the list faster.

+1
source

Definitely use regex expression. It makes no sense to write your own system when there is a very comprehensive system for this exact task. If you need to learn or update a regular expression, then check out this site, it's great: http://regexr.com

I would challenge myself.

0
source

All Articles