简体   繁体   English

检查字符串是否仅包含允许的字符

[英]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. 匹配器正常工作,但是当我输入类似“ 123A”的应用程序时崩溃。 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: 这是我的logcat错误:

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): 另外,使用matches()方法而不是find()来匹配整个输入字符串(您的问题是find()找到第一个匹配项,然后不尝试匹配其余匹配项):

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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