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

时间:2015-06-26 00:41:11

标签: java regex

假设我有一个如下字符串,我想检查至少有一个字符是否是大于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> 

4 个答案:

答案 0 :(得分:3)

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!");
    }

}

答案 1 :(得分:3)

使用Matcher classfind()。无论字符串是否包含匹配,它都会返回truefalse

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

答案 2 :(得分:3)

试试这个:

Sub
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
ws.Activate
Range("C100:F103").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Bulksheet").Select
Range("D1").End(xlDown).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Next
End Sub

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

答案 3 :(得分:2)

使用流的一种(可能)更有效的方式:

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