繁体   English   中英

Java正则表达式检查字符串是否包含1个字符(数字)> 0

[英]Java regex check if string contains 1 character (number) > 0

假设我有一个字符串如下,我想检查至少一个字符是否是一个大于0的数值(检查1非零元素编号)。 有没有办法在不运行拆分字符串和循环等的情况下执行此操作? 我假设有一个正则表达式解决方案,但我不知道很多正则表达式。

String x = "maark ran 0000 to the 23 0 1 3 000 0"

这应该通过

String x2 = "jeff ran 0 0 0000 00 0 0 times 00 0"

^这应该失败

我尝试过以下方法:

String line = fileScanner.nextLine();
if(!(line.contains("[1-9]+")) 
    <fail case>
else 
    <pass case> 
public boolean contains(CharSequence s)

此方法不将正则表达式作为参数。您需要使用:

    // compile your regexp
    Pattern pattern = Pattern.compile("[1-9]+");
    // create matcher using pattern
    Matcher matcher = pattern.matcher(line);
    // get result
    if (matcher.find()) {
        // detailed information
        System.out.println("I found the text '"+matcher.group()+"' starting at index "+matcher.start()+" and ending at index "+ matcher.end()+".");
        // and do something
    } else {
        System.out.println("I found nothing!");
    }

}

使用Matcher类的 find() 无论字符串是否包含匹配,它都返回truefalse

Pattern.compile("[1-9]").matcher(string).find();

尝试这个:

if (string.matches(".*[1-9].*"))
    <pass case>
else 
    <fail case>

非零数字的存在足以保证输入中存在非零值(某处)。

并且(可能)使用流更有效的方式:

s.chars().anyMatch((c)-> c >= '1' && c <= '9');

暂无
暂无

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

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