【问题标题】:RegEx for matching repeating [01] using capturing groups使用捕获组匹配重复 [01] 的正则表达式
【发布时间】:2019-09-29 07:32:45
【问题描述】:

我有一个可变长度的值字符串(实际上是位:1 和 0,32 的倍数)。例如:

010011011001110111100111011010001001100011101100100011100010100011110010100011001111111101101001

每个 32 位块都包含一个内部结构:前 8 位和接下来的 24 位属于同一个。

我喜欢

  • 获取每个 32 位块并
  • 每个块的内部结构

在一个正则表达式中。

我的方法

^(([01]{8})([01]{24})){0,}$

没有成功,因为它只匹配最后一个块。

这样的正则表达式可能吗?要找什么?我做错了什么?

【问题讨论】:

  • 你使用什么编程语言?
  • Java,但应该没关系吧?
  • 内部结构是什么意思?预期的输出应该是什么?
  • 使用这个:'(([01]{8})([01]{24}))' 并设置 'global' 标志,然后您将获得所有匹配项。
  • Java 没有 findall() 函数将这些值放入数组吗?您不必一次性匹配所有内容。

标签: regex regex-lookarounds regex-group regex-greedy


【解决方案1】:

我使用this tool 稍微修改了它:

(([0-1]{8})([0-1]{24}))

如果我理解正确,您可能不想将它与开始和结束字符绑定。您可以简单地在它周围使用另一个捕获组,并与您已经拥有的另外两个捕获组一起,根据需要提取数据。

正则表达式描述图

这个link 可以帮助你可视化你的表情:

JavaScript 测试演示

const regex = /(([0-1]{8})([0-1]{24}))/gm;
const str = `010011011001110111100111011010001001100011101100100011100010100011110010100011001111111101101001
`;
const subst = `Group #1: $1\nGroup #2: $2\nGroup #3: $3\n`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

性能测试

这个 sn-p 返回一百万次 for 循环的运行时间。

const repeat = 1000000;
const start = Date.now();

for (var i = repeat; i >= 0; i--) {
	const regex = /(([0-1]{8})([0-1]{24}))/gm;
	const str = `010011011001110111100111011010001001100011101100100011100010100011110010100011001111111101101001`;
	const subst = `\nGroup #1: $1\nGroup #2: $2\nGroup #3: $3`;

	var match = str.replace(regex, subst);
}

const end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match ??? ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. ? ");

【讨论】:

  • [0-1][01] 在基于 ASCII 的编码中是一样的。
  • 这成功了!为什么它不适用于我的 ...{0,} 扩展?
  • 你在用matcher.find()吗?
  • 好的,谢谢您的帮助!我将对此进行更深入的研究。
【解决方案2】:

在 java 中,您一次可以得到一个匹配项。

代码

// \G matches only exactly where the previous `find()` left off
// (?:^|\G) matches either at start of line or where previous `find()` left off
Pattern p = Pattern.compile("(?:^|\G)([01]{8})([01]{24})");
// inputString should not contain e.g. newline characters
Matcher m = p.matcher(inputString);
boolean lastMatchEnd = 0;
while (m.find()) {
    String firstPart = m.group(1);
    String secondPart = m.group(2);
    // ...
    // remember how far we got
    lastMatchEnd = m.end();
}
if (lastMatchEnd != inputString.length()) {
  // if we get here, there were garbage in the line that did not match
}

【讨论】:

    猜你喜欢
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多