-1

I have a String like "[5 TO 100]%" Which I want to get matched with the help of regex

5 and 100 from this String can get changed like 5 can be range from 1 to 999 and the same goes with 100

Others will be as it is, So Basically I want to match "[num1 TO num2]%"

--EDIT--

The duplicate target meets the requirement only partially because the string has non-digit characters (alphabets and special characters like [, ], and % as well).

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Jay Kolate
  • 57
  • 2
  • @Abra It did not worked, – Jay Kolate Mar 18 '21 at 10:50
  • When in doubt - [javadoc for Pattern](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html). @JayKolate perhaps post your code that's not working (the Regex pattern and how you use it]? – Mr R Mar 18 '21 at 10:55

1 Answers1

9

You can use the regex, (?i)\[[1-9][0-9]{0,2} TO [1-9][0-9]{0,2}\]%.

If you do not want the match to happen in a case-insensitive way, remove (?i).

Demo:

import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        Stream.of(
                "[5 TO 100]%",
                "[0 to 100]%",
                "[10 TO 15]%",
                "[999 to 1]%",
                "[1000 TO 100]%",
                "[5 TO 10000]%"
            ).forEach(s -> System.out.println(s.matches("(?i)\\[[1-9][0-9]{0,2} TO [1-9][0-9]{0,2}\\]%")));
    }
}

Output:

true
false
true
true
false
false

Explanation at regex101: enter image description here

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110