[英]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!");
}
}
嘗試這個:
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.