如何让正则表达式继续匹配模式?

问题描述 投票:0回答:1

我想出了以下正则表达式来匹配有效字符串中的第二个和第四个字符。 但是,我希望添加到此,以便第二个、第四个、第六个、第八个......等等,是匹配的。 这怎么可能?

任何帮助表示赞赏(我是新手!)

^([01])([01])([01])$

谢谢:)

更新:我设法更新它,以便它继续匹配。 然而,当我测试时,我每次都需要向字符串中添加额外的 4 个字符以增加匹配项。有什么办法可以将其更改为每 2 个字符吗?

(?:([01])([01])([01])( ))

例如 0101 将匹配(第二个和第四个字符)。

010101 - 仅匹配前四个字符 0101。
我希望这个匹配,因为第二个、第四个和第六个字符匹配。

01010101 将匹配(8 个字符)。

如果第二个、第四个、第六个、第八个、第十个......等等是相同的字符,它应该匹配。

c regex
1个回答
0
投票

我根本不会为此使用正则表达式;只需循环遍历字符串,确保其他每个字符都等于字符串的第二个字符,并且其他字符均为 0 或 1:

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

bool check_pattern(const char *s) {
  // make sure the first character is a 0 or 1
  if (!(s[0] == '0' || s[0] == '1')) {
    return false;
  }
  // make sure the second character is a 0 or 1.
  if (!(s[1] == '0' || s[1] == '1')) {
    return false;
  }
  // make sure the string is more than 2 characters long;
  if (!s[2]) {
    return false;
  }

  for (int i = 2; s[i]; i += 2) {
    // fail if current character is not a 0 or 1
    if (!(s[i] == '0' || s[i] == '1')) {
      return false;
    }
    // fail if the next character doesn't match the second character of
    // the string (this also catches an odd number of characters)
    if (s[i + 1] != s[1]) {
      return false;
    }
  }
  return true;
}

int main(int argc, char **argv) {
  if (argc != 2) {
    fprintf(stderr, "Usage: %s STRING\n", argv[0]);
    return EXIT_FAILURE;
  }
  if (check_pattern(argv[1])) {
    printf("%s matches!\n", argv[1]);
  } else {
    printf("%s doesn't match.\n", argv[1]);
  }
  return 0;
}

演示:

$ gcc -O -g -Wall -Wextra -o pat pat.c
$ ./pat 0101
0101 matches!
$ ./pat 0100
0100 doesn't match.
$ ./pat 01010101
01010101 matches!
$ ./pat 01010001
01010001 doesn't match.
© www.soinside.com 2019 - 2024. All rights reserved.