如何检查 java 中的二进制点数验证?
how to check Binary point number validation in java?
示例:-
有效二进制数 = 1010111 // true
有效二进制小数点数 = 101011.11 // true
无效二进制数 = 152.35 // false
如何检查?
public boolean isBinary(int num)
{
// here you may want to check for negative number & return false if it is -ve number
while (num != 0) {
if (num % 10 > 1) {
return false; // If the digit is greater than 1 return false
}
num = num / 10;
}
return true;
}
您可以使用正则表达式,[01]*\.?[01]+
演示:
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]+");
}
}
输出:
1010111 => true
101011.11 => true
101.011.11 => false
152.35 => false
regex101处正则表达式的解释:
如果您还想匹配以可选 0b
或 0B
开头的数字,您可以使用正则表达式 (?:0[bB])?[01]*\.?[01]+
演示:
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]+");
}
}
输出:
1010111 => true
0b1010111 => true
0B1010111 => true
1b010111 => false
010B10111 => false
101011.11 => true
101.011.11 => false
152.35 => false
regex101处正则表达式的解释:
示例:-
有效二进制数 = 1010111 // true
有效二进制小数点数 = 101011.11 // true
无效二进制数 = 152.35 // false
如何检查?
public boolean isBinary(int num)
{
// here you may want to check for negative number & return false if it is -ve number
while (num != 0) {
if (num % 10 > 1) {
return false; // If the digit is greater than 1 return false
}
num = num / 10;
}
return true;
}
您可以使用正则表达式,[01]*\.?[01]+
演示:
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]+");
}
}
输出:
1010111 => true
101011.11 => true
101.011.11 => false
152.35 => false
regex101处正则表达式的解释:
如果您还想匹配以可选 0b
或 0B
开头的数字,您可以使用正则表达式 (?:0[bB])?[01]*\.?[01]+
演示:
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]+");
}
}
输出:
1010111 => true
0b1010111 => true
0B1010111 => true
1b010111 => false
010B10111 => false
101011.11 => true
101.011.11 => false
152.35 => false
regex101处正则表达式的解释: