简体   繁体   English

正则表达式Javascript二进制数验证

[英]Regular Expression Javascript binary number validation

i am trying to convert binary to decimal value我正在尝试将二进制值转换为十进制值

I am need a regular expression for validating the binary number.我需要一个正则表达式来验证二进制数。

//for now i am using 

var binary="1234"

 /^-{0,1}\d+$/g.test(binary)

//my output:

1

but i want the output to say not in binary format.但我希望输出不是二进制格式。

Thanks in advance提前致谢

它匹配每个找到的条目,而不仅仅是第一个。

/^-{0,1}\d+$/g.test(binary)

validates any positive or negative integer ( \\d means "any digit"; also -{0,1} can be written as -? ).验证任何正整数或负整数( \\d表示“任何数字”;也-{0,1}可以写成-? )。 The g global flag doesn't make much sense here since you want to validate an entire string, not a substring in a longer, multi-line string (which wouldn't work anyway because the anchors ^ and $ make sure of that already). g全局标志在这里没有多大意义,因为您想验证整个字符串,而不是更长的多行字符串中的子字符串(无论如何都行不通,因为锚点^$已经确保了这一点) .

Try this instead:试试这个:

/^[01]+$/.test(binary)   
/[^0-1]/g.test(binary)

In this way checks all characters that aren't 0 or 1.以这种方式检查所有不是 0 或 1 的字符。

Probably isn't the best way to do it, but it worked for me.可能不是最好的方法,但它对我有用。

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

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