Java String - 查看字符串是否仅包含数字而不包含字母

Red*_*tcc 167 java string if-statement

我有一个字符串,我在我的应用程序中加载,它从数字变为字母等.我有一个简单的if声明,看它是否包含字母或数字,但有些东西不能正常工作.这是一个片段.

String text = "abc"; 
String number; 

if (text.contains("[a-zA-Z]+") == false && text.length() > 2) {
    number = text; 
}
Run Code Online (Sandbox Code Playgroud)

虽然text变量确实包含字母,但条件返回为true.的和&&应作为EVAL两个条件不必是true为了处理number = text;

==============================

解:

我能够通过使用此问题的评论提供的以下代码来解决这个问题.所有其他帖子也有效!

我使用的工作来自第一条评论.虽然提供的所有示例代码似乎也是有效的!

String text = "abc"; 
String number; 

if (Pattern.matches("[a-zA-Z]+", text) == false && text.length() > 2) {
    number = text; 
}
Run Code Online (Sandbox Code Playgroud)

Ada*_*iss 324

如果您要将数字作为文本处理,请更改:

if (text.contains("[a-zA-Z]+") == false && text.length() > 2){
Run Code Online (Sandbox Code Playgroud)

至:

if (text.matches("[0-9]+") && text.length() > 2) {
Run Code Online (Sandbox Code Playgroud)

而不是检查该字符串的包含字母字符,检查,以确保它包含只有 NUMERICS.

如果您确实想要使用数值,请使用Integer.parseInt()Double.parseDouble()正如其他人在下面解释的那样.


作为旁注,将布尔值与true或比较通常被认为是不好的做法false.只需使用if (condition)if (!condition).

  • 您可能想要添加锚点(例如`^ [0-9] + $`),否则`abc123def`将被视为数字. (21认同)
  • 不需要调用`&&(text.length()> 2)`.所有东西都可以用正则表达式来检查:`if(text.matches("[0-9] {3,}")` (14认同)
  • 我不认为这是必需的.`matches()`当且仅当它从头到尾完全匹配时才返回true. (9认同)
  • "^ - ?\ d + \.?\ d*$"将比较整个字符串,只有在有效数字(包括底片和小数)时才匹配.例如,它将匹配1,10,1.0,-1,-1.0等.它也将匹配"1".但这通常可以解析. (4认同)

Dhr*_*hah 20

您还可以使用Apache Commons中的NumberUtil.isCreatable(String str)

  • 我不认为`NumberUtil.isCreatable(String str)`对于原始问题的要求是正确的.例如,`NumberUtil.isCreatable("09")`返回`false`,即使``09"`*只包含数字*. (3认同)

tok*_*khi 12

我就是这样做的:

if(text.matches("^[0-9]*$") && text.length() > 2){
    //...
}
Run Code Online (Sandbox Code Playgroud)

$将避免部分匹配例如; 1B.


Ama*_*pta 10

为了简单地检查它只包含 ALPHABETS 的字符串,请使用以下代码:

if (text.matches("[a-zA-Z]+"){
   // your operations
}
Run Code Online (Sandbox Code Playgroud)

为了简单地检查它只包含 NUMBER 的字符串,请使用以下代码:

if (text.matches("[0-9]+"){
   // your operations
}
Run Code Online (Sandbox Code Playgroud)

希望这会对某人有所帮助!


jaf*_*mlp 9

使用 Java 8 流和 lambda 的解决方案

String data = "12345";
boolean isOnlyNumbers = data.chars().allMatch(Character::isDigit);
Run Code Online (Sandbox Code Playgroud)


Ant*_*n R 7

性能方面parseInt比其他解决方案要糟糕得多,因为至少需要异常处理.

我已经运行了jmh测试并发现使用charAt和比较字符和边界字符迭代字符串是测试字符串是否只包含数字的最快方法.

JMH测试

测试比较Character.isDigitvs Pattern.matcher().matchesvs Long.parseLongvs check char值的性能.

这些方法可以为非ascii字符串和包含+/-符号的字符串产生不同的结果.

测试在吞吐量模式下运行(越大越好),有5次预热迭代和5次测试迭代.

结果

请注意,这parseLongisDigit第一次测试负载慢近100倍.

## Test load with 25% valid strings (75% strings contain non-digit symbols)

Benchmark       Mode  Cnt  Score   Error  Units
testIsDigit    thrpt    5  9.275 ± 2.348  ops/s
testPattern    thrpt    5  2.135 ± 0.697  ops/s
testParseLong  thrpt    5  0.166 ± 0.021  ops/s

## Test load with 50% valid strings (50% strings contain non-digit symbols)

Benchmark              Mode  Cnt  Score   Error  Units
testCharBetween       thrpt    5  16.773 ± 0.401  ops/s
testCharAtIsDigit     thrpt    5  8.917 ± 0.767  ops/s
testCharArrayIsDigit  thrpt    5  6.553 ± 0.425  ops/s
testPattern           thrpt    5  1.287 ± 0.057  ops/s
testIntStreamCodes    thrpt    5  0.966 ± 0.051  ops/s
testParseLong         thrpt    5  0.174 ± 0.013  ops/s
testParseInt          thrpt    5  0.078 ± 0.001  ops/s
Run Code Online (Sandbox Code Playgroud)

测试套件

@State(Scope.Benchmark)
public class StringIsNumberBenchmark {
    private static final long CYCLES = 1_000_000L;
    private static final String[] STRINGS = {"12345678901","98765432177","58745896328","35741596328", "123456789a1", "1a345678901", "1234567890 "};
    private static final Pattern PATTERN = Pattern.compile("\\d+");

    @Benchmark
    public void testPattern() {
        for (int i = 0; i < CYCLES; i++) {
            for (String s : STRINGS) {
                boolean b = false;
                b = PATTERN.matcher(s).matches();
            }
        }
    }

    @Benchmark
    public void testParseLong() {
        for (int i = 0; i < CYCLES; i++) {
            for (String s : STRINGS) {
                boolean b = false;
                try {
                    Long.parseLong(s);
                    b = true;
                } catch (NumberFormatException e) {
                    // no-op
                }
            }
        }
    }

    @Benchmark
    public void testCharArrayIsDigit() {
        for (int i = 0; i < CYCLES; i++) {
            for (String s : STRINGS) {
                boolean b = false;
                for (char c : s.toCharArray()) {
                    b = Character.isDigit(c);
                    if (!b) {
                        break;
                    }
                }
            }
        }
    }

    @Benchmark
    public void testCharAtIsDigit() {
        for (int i = 0; i < CYCLES; i++) {
            for (String s : STRINGS) {
                boolean b = false;
                for (int j = 0; j < s.length(); j++) {
                    b = Character.isDigit(s.charAt(j));
                    if (!b) {
                        break;
                    }
                }
            }
        }
    }

    @Benchmark
    public void testIntStreamCodes() {
        for (int i = 0; i < CYCLES; i++) {
            for (String s : STRINGS) {
                boolean b = false;
                b = s.chars().allMatch(c -> c > 47 && c < 58);
            }
        }
    }

    @Benchmark
    public void testCharBetween() {
        for (int i = 0; i < CYCLES; i++) {
            for (String s : STRINGS) {
                boolean b = false;
                for (int j = 0; j < s.length(); j++) {
                    char charr = s.charAt(j);
                    b = '0' <= charr && charr <= '9';
                    if (!b) {
                        break;
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

更新于2018年2月23日

  • 再添加两个案例 - 一个使用charAt而不是创建额外的数组,另一个使用IntStreamchar代码
  • 如果找到循环测试用例的非数字,则添加立即中断
  • 对于循环测试用例,返回空字符串的false

更新于2018年2月23日

  • 再添加一个测试用例(最快的!),它不使用流来比较char值


Abd*_*ull 6

Apache Commons Lang提供了org.apache.commons.lang.StringUtils.isNumeric(CharSequence cs),它将 a 作为参数String并检查它是否由纯数字字符组成(包括来自非拉丁文字的数字)。false如果有空格、减号、加号等字符和逗号和点等小数点分隔符,则该方法返回。

该类的其他方法允许进一步的数字检查。


小智 6

StringUtils.isNumeric("1234")
Run Code Online (Sandbox Code Playgroud)

这很好用。