正则表达式"\\ d +"在字符串中找到两次整数:"{10}".匹配器匹配10和0

oll*_*llo 1 regex matcher bitset

我使用正则表达式将BitSet normal toString转换为二进制字符串.例如,如果myBitSet.toString()返回{10},它会设置第10位和第0位,但应该只设置第10位.

    ...
    Matcher m = Pattern.compile("(?=(" + "\\d+" + "))").matcher(temp);
    while(m.find()) {
        String test2 = m.group(1);
        answer.setCharAt((2*OpSize -1 - Integer.valueOf(m.group(1))), '1');

    }
    .....
Run Code Online (Sandbox Code Playgroud)

Tim*_*ker 6

你的问题是正则表达式使用前瞻断言 (?=...),找到重叠匹配.我无法想到你在这种情况下需要的原因.

尝试删除它; 这将确保只找到整个数字.您也不需要捕获组,因为您可以简单地使用整个匹配.group(0):

Matcher m = Pattern.compile("\\d+").matcher(temp);
while(m.find()) {
    String test2 = m.group(0); // why is this here? You're not using it.
    answer.setCharAt((2*OpSize -1 - Integer.valueOf(m.group(0))), '1');
}
Run Code Online (Sandbox Code Playgroud)