简体   繁体   中英

Checking if string contains only allowed characters

I want to check if my string contains only allowed character. Matcher works properly, but when I input something like this "123A" app crashes. For only letters it work properly(error). How can I do that?

My code:

pattern = Pattern.compile("[0-9]");
matcher = pattern.matcher(stNumber);
  if(matcher.find())
else
   error

This is my logcat error:

03-07 21:49:50.917    1891-1891/com.converter_numeralsystem.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.converter_numeralsystem.app, PID: 1891
java.lang.NumberFormatException: Invalid long: "112a"
        at java.lang.Long.invalidLong(Long.java:124)
        at java.lang.Long.parse(Long.java:361)
        at java.lang.Long.parseLong(Long.java:352)
        at java.lang.Long.parseLong(Long.java:318)
        at com.converter_numeralsystem.app.MainActivity.calculate(MainActivity.java:121)
        at com.converter_numeralsystem.app.MainActivity.onClick(MainActivity.java:246)
        at android.view.View.performClick(View.java:4438)
        at android.view.View$PerformClick.run(View.java:18422)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)

If you want to allow only numbers, you should use a regular expression to match the whole string (add + to check for at least one digit). Also, use matches() method instead of find() to match the whole input string (your problem is that find() finds the first match and then doesn't try to match the rest):

pattern = Pattern.compile("[0-9]+");
matcher = pattern.matcher(stNumber);
  if(matcher.matches())
else
   error

Try

pattern = Pattern.compile("[0-9]+");

Or

pattern = Pattern.compile("\\d+");

Also use

if(matcher.match())

Instead of

if(matcher.find())

如果您有只想引入数字的编辑文本,则可以将此属性添加到xml文件中的编辑文本中:

android:digits="0123456789"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM