javabinarynumber-systems

how to check Binary point number validation in java?


Examples:-

Valid Binary number = 1010111 // true

Valid Binary point number = 101011.11 // true

Invalid Binary number = 152.35 // false

How to check?


Solution

  • You can use the regex, [01]*\.?[01]+

    Demo:

    import java.util.stream.Stream;
    
    public class Main {
        public static void main(String[] args) {
            //Test
            Stream.of(
                        "1010111",
                        "101011.11",
                        "101.011.11",
                        "152.35"
                    ).forEach(s -> System.out.println(s + " => " + isBinary(s)));
        }
        
        static boolean isBinary(String s) {
            return s.matches("[01]*\\.?[01]+");
        }
    }
    

    Output:

    1010111 => true
    101011.11 => true
    101.011.11 => false
    152.35 => false
    

    Explanation of the regex at regex101:

    enter image description here

    If you also want to match a number starting with optional 0b or 0B, you can use the regex, (?:0[bB])?[01]*\.?[01]+

    Demo:

    import java.util.stream.Stream;
    
    public class Main {
        public static void main(String[] args) {
            //Test
            Stream.of(
                        "1010111",
                        "0b1010111",
                        "0B1010111",
                        "1b010111",
                        "010B10111",
                        "101011.11",
                        "101.011.11",
                        "152.35"
                    ).forEach(s -> System.out.println(s + " => " + isBinary(s)));
        }
        
        static boolean isBinary(String s) {
            return s.matches("(?:0[bB])?[01]*\\.?[01]+");
        }
    }
    

    Output:

    1010111 => true
    0b1010111 => true
    0B1010111 => true
    1b010111 => false
    010B10111 => false
    101011.11 => true
    101.011.11 => false
    152.35 => false
    

    Explanation of the regex at regex101:

    enter image description here