Reputation: 29
Say I have a String as below and I would like to check if at least one character is a numerical value greater than 0 (check for 1 non zero element number). Is there a way to do this without running splitting the String and making a loop etc.? I assume there is a regex solution but I do not know much regex.
String x = "maark ran 0000 to the 23 0 1 3 000 0"
^this should pass
String x2 = "jeff ran 0 0 0000 00 0 0 times 00 0"
^this should fail
I have tried the following:
String line = fileScanner.nextLine();
if(!(line.contains("[1-9]+"))
<fail case>
else
<pass case>
Upvotes: 2
Views: 2141
Reputation: 3168
And a (possibly) more efficient way using streams:
s.chars().anyMatch((c)-> c >= '1' && c <= '9');
Upvotes: 2
Reputation: 425398
Try this:
if (string.matches(".*[1-9].*"))
<pass case>
else
<fail case>
The presence of a non-zero digit is enough to guarantee there's a non-zero value (somewhere) in the input.
Upvotes: 3
Reputation: 49656
public boolean contains(CharSequence s)
This method does not take a regular expression as a parameter.You need use:
// 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!");
}
}
Upvotes: 3
Reputation: 4551
Use find()
of the Matcher class. It returns true
or false
whether a string contains a regex match or not.
Pattern.compile("[1-9]").matcher(string).find();
Upvotes: 3