如果不是0和1,则返回false

时间:2014-04-10 07:15:02

标签: java regex

我有以下代码将二进制(作为字符串输入)转换为十进制,如果输入包含字符串1或{{1以外的任何内容,我想给出错误消息}}

0

我很确定我正在寻找的是一个正则表达式,但在搜索之后,我比起初时更加困惑。

2 个答案:

答案 0 :(得分:2)

检查字符串中是否有除0和1之外的任何字符:

yourString.matches("[^01]")

spOOm提出的解决方案

!yourString.matches("[01]+")

表示the string does not have any seuquence of 0 or 1, 这并不是问题所暗示的:

I'd like to give an error message if the input contains
anything other than the strings 1 or 0

答案 1 :(得分:1)

这将匹配仅包含0和1的字符串。

theString.matches("^[01]+$")
  1. 字符类[01]匹配0或1的
  2. +表示匹配1个或更多正在进行的字符类(0或更多0或1)
  3. ^和$表示整个字符串必须匹配