Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

java - Check non-numeric characters in string

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can check this with a regex.

Suppose that (numeric values only):

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

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...