簡體   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