'Regex to describe binary numbers

I want to have a regular expression to describe all binary numbers (consisting only of 0 and 1).

So it should work for 100 0 101001 11 000 but not for the 1 and 0 parts in hello1001and011. It really should only match to all digit numbers.

I wanted to write ^(0|1)(0|1)*(0|1)$ to mark that it should begin and end with a zero or one and in the middle can be arbitrary many 0 and 1 but it doesn't match anything.

In my lecture we just saw operations like | , + , * , ^ , $ , . , as well as \d and \w.

Can someone please help me to find my error/give me a working regular expression?



Solution 1:[1]

You can simply use word boundaries \b:

\b[01]+\b

In your regex you're using ^ (beginning of line or text) and $ (end of line or text), which means it tries to match the whole string, rather than matching separate words/numbers.

Solution 2:[2]

[0*1*]*[1*0*]*

Hope this helps and it passes every binary number.

Solution 3:[3]

Check if it only contains 1 or 0, n times:

[0-1]+

regex description src: https://regex101.com

Solution 4:[4]

If the given sting is a binary number, it will return true. Otherwise, it will return false.

const str1 = '10101';
const str2 = '1002s1';
const regex = new RegExp('^[0-1]{1,}$','g');

console.log(regex.test(str1));
console.log(regex.test(str2));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kirill Polishchuk
Solution 2 Mehant Kammakomati
Solution 3 ericmp
Solution 4 Ovi