如何用正则表达式检测奇数长度01的序列

Yod*_*oda 0 java regex matcher

我想匹配具有奇数长度的01的正则表达式字符串.例:"0","001","111","11111" etc.

这个想法是奇数长度的序列是0或1,然后是0或1对.但我的正则表达式似乎不起作用.我做的:

String regex = "[0-1]{1}[[0-1]{2}]{0,}";
    String txt = "01";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(txt);

        System.out.println(m.matches());
Run Code Online (Sandbox Code Playgroud)

Nik*_*zov 5

试试这个:

String regex = "[01]([01][01])*";
"00011".matches(regex) => true
"0001".matches(regex) => false
Run Code Online (Sandbox Code Playgroud)