假设我有一个字符串,如下所示,我想检查是否至少有一个字符是大于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> 发布于 2015-06-26 08:46:16
public boolean contains(CharSequence s)此方法不接受正则表达式,因为需要使用parameter.You:
// 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!");
}}
发布于 2015-06-26 08:46:35
使用Matcher class的find()。无论字符串是否包含regex匹配,它都会返回true或false。
Pattern.compile("[1-9]").matcher(string).find();发布于 2015-06-26 08:54:38
试试这个:
if (string.matches(".*[1-9].*"))
<pass case>
else
<fail case>非零数字的存在足以保证在输入中存在非零值(在某处)。
https://stackoverflow.com/questions/31063092
复制相似问题