检查字符串中的非数字字符 [英] Check non-numeric characters in string

查看:70
本文介绍了检查字符串中的非数字字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查字符串是否仅包含数字字符或它也包含字母数字字符.

I want to check whether the String contains only numeric characters or it contains alpha-numeric characters too.

我必须在数据库事务中实施此检查,该事务将要获取并通过该检查传递约十万条记录,因此我需要优化性能的答案.

I have to implement this check in database transaction where about a hundred-thousand records are going to be fetched and passed through this check, so I need optimized performance answer.

当前,我已经通过try-catch块实现了这一点:我在try块中的Integer中解析了字符串,并在catch块中检查了NumberFormatException.请提出建议,如果我错了.

Currently, I have implemented this through a try-catch block: I parsed the string in Integer in try block and checked for the NumberFormatException in the catch block. Please suggest if I'm wrong.

推荐答案

您可以使用正则表达式进行检查.

You can check this with a regex.

假设(仅数字值):

String a = "493284835";
a.matches("^[0-9]+$"); // returns true

假设(仅字母数字值):

Suppose that (alphanumeric values only):

String a = "dfdf4932fef84835fea";
a.matches("^([A-Za-z]|[0-9])+$"); // returns true

正如Pangea在评论区所说:

As Pangea said in the comments area :

如果性能至关重要,则最好编译正则表达式.参见下面的示例:

If the performance are critical, it's preferrable to compile the regex. See below for an example :

String a = "dfdf4932fef84835fea";
Pattern pattern = Pattern.compile("^([A-Za-z]|[0-9])+$");
Matcher matcher = pattern.matcher(a);

if (matcher.find()) {
    // it's ok
}

这篇关于检查字符串中的非数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆