简体   繁体   中英

minimum number in a string should be 1 regex validation?

I have a String which I need to match. Meaning it should only contains a number followed by space or just a number and minimum number should be 1 always. For ex:

3 1 2
1 p 3
6 3 2
0 3 2

First and third are valid string and all other are not.

I came up with below regex but I am not sure how can I check for minimum number in that string should be 1 always?

str.matches("(\\d|\\s)+")

Regex used from here

Just replace \\\\d with [1-9] .

\\\\d is just a shorthand for the class [0-9] .

This is a better regex though: ([1-9]\\\\s)*[1-9]$ , as it takes care of double digit issues and won't allow space at the end.

Not everything can or should be solved with regular expressions.

You could use a simple expression like

str.matches("((\\d+)\\s)+")

or something alike to simply check that your input line contains only groups of digits followed by one or more spaces.

If that matches, you split along the spaces and for each group of digits you turn it into a number and validate against the valid range.

I have a gut feeling that regular expressions are actually not sufficient for the kind of validation you need.

Regex is part of the solution. But I don't think that regex alone can solve your problem.

This is my proposed solution:

private static boolean isValid(String str) {
    Pattern pattern = Pattern.compile("[(\\d+)\\s]+");
    Matcher matcher = pattern.matcher(str);

    return matcher.matches() && Arrays.stream(Arrays.stream(matcher.group().split(" "))
            .mapToInt(Integer::parseInt)
            .toArray()).min().getAsInt() == 1;
}

Pay attention to the mathing type: matcher.matches() - to check match against the entire input. (don't use matcher.find() - because it will not reject invalid input such as "1 p 2")

If it should only contains a number followed by space or just a number and minimum number should be 1 and number can also be larger than 10 you might use:

^[1-9]\\d*(?: [1-9]\\d*)*$

Note that if you want to match a space only, instead of using \\s which matches more you could just add a space in the pattern.

Explanation

  • ^ Assert the start of the string
  • [1-9]\\\\d* Match a number from 1 up
  • (?: [1-9]\\\\d*)* Repeat a number from 1 up with a prepended space
  • $ Assert end of the string

Regex demo

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