简体   繁体   中英

Java regex check if string contains 1 character (number) > 0

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

}

Use find() of the Matcher class . It returns true or false whether a string contains a match or not.

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

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.

并且(可能)使用流更有效的方式:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM