问题是找到所有在 1 和 0 之间交替的位序列,即那些连续不超过 1 或 0 的位序列并将其返回到列表中。
到目前为止我做了什么
public static List<String> findBits(String text) {
Pattern pattern = Pattern.compile("([01])(?!\\1)([01])(?:\\1\\2)*\\1?|(?<!\\S)[01](?!\\S)|1.|0.", Pattern.DOTALL);
Matcher matcher = pattern.matcher(text);
return matcher.results()
.map(String::valueOf)
.collect(Collectors.toList());
它应该返回这里没有二进制数 3434。-> [] 空列表
嘿 friend ,这是 1。-> [1]
这些是 1001, 1010, 1011, 1100, 1101 -> [1010]
这是一个长值 1010101010 和这个也是 1010101010101011 -> [1010101010]
0 + 0 也是一个 0。-> [0,0,0]
最佳答案
您可以使用
\b(?!\d*(\d)\1)[10]+\b
见regex demo .在 Java 中,用
"\\b(?!\\d*(\\d)\\1)[10]+\\b"
声明它.细节
\b
- 一个词的边界(?!\d*(\d)\1)
- 当前号码中不允许重复的后续数字[10]+
- 一个或多个 1
或 0
字符 \b
- 一个词的边界见 Java demo :
public static Pattern pattern = Pattern.compile("\\b(?!\\d*(\\d)\\1)[10]+\\b");
public static List<String> findBits(String text) {
Matcher matcher = pattern.matcher(text);
return pattern.matcher(text)
.results()
.map(MatchResult::group)
.collect(Collectors.toList()); //.toArray(String[]::new);
}
public static void main (String[] args) throws java.lang.Exception
{
List<String> r = findBits("no binary numbers here 3434. Hey friend this is a 1. Those are 1001, 1010, 1011, 1100, 1101. This is a long value 1010101010 and this one as well 1010101010101011. 0 + 0 is a also a 0.");
System.out.println(r);
}
// => [1, 1010, 1010101010, 0, 0, 0]
关于java - 如何使用 REGEX 找到交替的 1 和 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67471113/