简体   繁体   English

如何确定一个数字是否为二进制数并且只有一个正则表达式且有偶数个零?

[英]How to determine if a number is binary and has an even amount of zeros with only one regex?

I want a regex to determine if a number is binary and if it has an even amount of zeros in it.我想要一个正则表达式来确定一个数字是否是二进制的,以及它是否有偶数个零。

For example, if we consider these 3 numbers:例如,如果我们考虑这 3 个数字:

  • 10001010 10001010
  • 00010010 00010010
  • 45671892 45671892

I want the regex to match the following:我希望正则表达式匹配以下内容:

  • 10001010 //Does NOT match because it has an uneven amount of zeros 10001010 //不匹配,因为它的零数量不均匀
  • 00010010 //Does match because it has an even amount of zeros 00010010 //匹配,因为它有偶数个零
  • 45671892 //Does not match because it is not a binary number 45671892 //不匹配,因为不是二进制数

The current solution is the following:目前的解决方案如下:

[1]*(0[1]*0[1]*)*

I tested it with https://regex101.com/ and it works for me.我用https://regex101.com/对其进行了测试,它对我有用。 The question is still online just to see if anyone can come up with a more efficient solution问题还在网上,只是想看看有没有人能提出更有效的解决方案

I am thankful for every help.我感谢每一个帮助。

Thank you in advance!先感谢您!

^[1]*(0[1]*0[1]*)*$

which can be interpreted in the following way:可以用以下方式解释:

find any number of 1 followed by pairs of 00 with optional one or more 1 s in between.找到任意数量的1后跟成对的00中间有可选的一个或多个1

You can use Long#parseLong to check if the given number string represents a binary number or not.您可以使用Long#parseLong来检查给定的数字字符串是否代表二进制数。 If yes, you can get a stream out of the number string, filter for 0 , count the number of 0 s and check if the count is divisible by 2 or not to determine if it has odd or even number of 0 s.如果是的话,你可以得到一个流出来的串号,过滤器为0 ,算上数量0秒和检查如果计数整除2或不确定它是否有奇数或偶数0秒。

public class Main {
    public static void main(String[] args) {
        String[] arr = { "10001010", "00010010", "45671892" };

        for (String s : arr) {
            // Check if the number string is binary
            try {
                // Can validate up to 64 bits
                Long.parseLong(s, 2);
                if (s.chars().filter(c -> c == '0').count() % 2 == 0) {
                    System.out.println(s + " represents a binary number and has an even number of 0s.");
                } else {
                    System.out.println(s + " represents a binary number and has an odd number of 0s.");
                }
            } catch (Exception e) {
                System.out.println(s + " does not represent a binary number.");
            }
        }
    }
}

Output:输出:

10001010 represents a binary number and has an odd number of 0s.
00010010 represents a binary number and has an even number of 0s.
45671892 does not represent a binary number.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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