问题描述
我在整个应用程序中加载了一个字符串,它从数字变为字母等等.我有一个简单的 if
语句来查看它是否包含字母或数字,但是有些东西不能正常工作.这是一个片段.
I have a string that I load throughout my application, and it changes from numbers to letters and such. I have a simple if
statement to see if it contains letters or numbers but, something isn't quite working correctly. Here is a snippet.
String text = "abc";
String number;
if (text.contains("[a-zA-Z]+") == false && text.length() > 2) {
number = text;
}
尽管 text
变量确实包含字母,但条件返回为 true
.和 &&
应该评估为两个条件都必须为 true
才能处理 number = text;
Although the text
variable does contain letters, the condition returns as true
. The and &&
should eval as both conditions having to be true
in order to process the number = text;
================================
==============================
解决方案:
我能够通过使用此问题的评论提供的以下代码来解决此问题.所有其他帖子也有效!
I was able to solve this by using this following code provided by a comment on this question. All other post are valid as well!
我使用的有用的东西来自第一条评论.尽管提供的所有示例代码似乎也有效!
What I used that worked came from the first comment. Although all the example codes provided seems to be valid as well!
String text = "abc";
String number;
if (Pattern.matches("[a-zA-Z]+", text) == false && text.length() > 2) {
number = text;
}
推荐答案
如果您要将数字作为文本处理,请更改:
If you'll be processing the number as text, then change:
if (text.contains("[a-zA-Z]+") == false && text.length() > 2){
到:
if (text.matches("[0-9]+") && text.length() > 2) {
与其检查字符串是否不包含字母字符,而是检查以确保它仅包含数字.
Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.
如果您确实想使用数值,请使用 Integer.parseInt()
或 Double.parseDouble()
,正如其他人在下面解释的那样.
If you actually want to use the numeric value, use Integer.parseInt()
or Double.parseDouble()
as others have explained below.
作为旁注,将布尔值与 true
或 false
进行比较通常被认为是不好的做法.只需使用 if (condition)
或 if (!condition)
.
As a side note, it's generally considered bad practice to compare boolean values to true
or false
. Just use if (condition)
or if (!condition)
.
这篇关于Java String - 查看一个字符串是否只包含数字而不包含字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2