java - 如何使用 REGEX 找到交替的 1 和 0
问题描述
问题是找到所有在 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。-> []空列表
嘿,朋友,这是 1。-> [1]
这些是 1001、1010、1011、1100、1101 -> [1010]
这是一个长值 1010101010 而这个也是 1010101010101011 -> [1010101010]
0 + 0 也是 0。-> [0,0,0]
解决方案
您可以使用
\b(?!\d*(\d)\1)[10]+\b
请参阅正则表达式演示。
在 Java 中,使用"\\b(?!\\d*(\\d)\\1)[10]+\\b"
.
细节
\b
- 单词边界(?!\d*(\d)\1)
- 当前号码中不允许出现重复的后续数字[10]+
- 一个或多个1
或0
字符\b
- 单词边界
查看Java 演示:
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]
推荐阅读
- python - 在 python 中为简单的数据分析脚本部署灵活的用户界面
- nlp - HuggingFace 转换器 - 使用上下文编码长输入
- highcharts - 无法从 CDN 加载 Highstock 作为 AMD 模块
- selenium - .feature 文件的 Gherkin 通用数据文件 (excel)
- python - 即使 DataFrame 为空,也可以使用 Pandas .apply() 创建新列
- azure - 使用 Azure 流分析 HoppingWindow 函数进行事件处理(每天 1700 万个事件) - 24 小时窗口,1 分钟跃点
- laravel-8 - Passing outer function parameter to inner function Laravel
- typescript - Error: expected 201 "Created", got 403 "Forbidden" - only on VM and Jenkins (test phase - rush test:e2e)
- google-visualization - Can columns in google chart be assigned multiple roles?
- javascript - how to delete column in excel sheets using NodeJs or nodejs node modules