0

I am implementing the code to check whether user input has valid ascii code or not. In order to do that, I found some simple way like below,

if (!firstName.matches("\\p{ASCII}*")) { 
    return error;   
}

I tested it in my local which is windows os based, I found that it worked well.

After testing, I deployed into our QA which is on linux system, it never works, it returns error regardless of valid ascii or not. Does anybody have this kind of problem before? Could you please give some advice?

Anna Lee
  • 909
  • 1
  • 17
  • 37
  • Please post a [mcve] –  May 12 '17 at 19:32
  • http://stackoverflow.com/questions/3585053/in-java-is-it-possible-to-check-if-a-string-is-only-ascii – Devendra Lattu May 12 '17 at 19:34
  • I’m guessing the String contains non-printing characters. Try printing the length of the String, and the integer value of each character in the String. – VGR May 12 '17 at 19:43
  • I think @VGR and @RC are saying the same thing. You probably don't need to test `matches`, you need to understand and control your test data (`firstName`). BTW—allowing a person's name to contain control characters (such as ␊ [U+000A](http://www.unicode.org/charts/nameslist/index.html)) but not extremely common letter characters (such as é) is pretty odd—unless you are totally certain that your storage or other system is limited to ASCII. – Tom Blodget May 13 '17 at 14:00

1 Answers1

0

Try this regex:

^[\\u0000-\\u007F]*$

or ^[ -~]*$ for printable ASCII characters (all characters between space and tilde)

Michael Kazarian
  • 4,376
  • 1
  • 21
  • 25