aloha
aloha

Reputation: 39

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?

Upvotes: 3

Views: 12975

Answers (4)

Abu Sayed
Abu Sayed

Reputation: 187

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));

Upvotes: 0

ericmp
ericmp

Reputation: 2257

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

[0-1]+

regex description src: https://regex101.com

Upvotes: 0

Mehant Kammakomati
Mehant Kammakomati

Reputation: 880

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

Hope this helps and it passes every binary number.

Upvotes: 0

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

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.

Upvotes: 6

Related Questions