(C ++)确定不匹配的正则表达式捕获组

时间:2018-04-19 00:08:31

标签: c++ regex regex-group

我想检查密码是否符合以下要求:

它应该:

  • 包含至少1个小写字母(ASCII 97-122)
  • 至少包含1个字母(65-90)
  • 至少包含1位数字
  • 包含至少1个特殊字符(33-47,58-64,91-96,123-126)
  • 的长度介于8到20个字符之间

它还应该告诉我哪些要求没有达到。

鉴于以下表达式,我可以使用std::regex

中的regex_match()对其进行验证
regex re("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!-/:-@[-`{-~])(\\S){8,20}$");

但这样我才能知道它是否匹配,因为它返回boolean

鉴于此,我尝试在向表达式添加一些捕获组之后迭代match_results,如下所示。

std::string str("AAAaaa111$$$");
std::regex rx("^((?=.*[a-z]).*)((?=.*[A-Z]).*)((?=.*[0-9]).*)((?=.*[!-/:-@[-`{-~]).*)(\\S){8,20}$");
std::match_results< std::string::const_iterator > mr;

std::regex_search(str, mr, rx);

std::cout << "size: " << mr.size() << '\n'; // 6 or 0 only ?
for (int i = 0; i < mr.size(); i++) {
    std::cout << "index: " << i << "\t --> \t" << mr.str(i) << endl;
}

if (regex_match(str, rx)) {
    cout << "tests passed" << endl;
}
else {
    cout << "tests failed" << endl;
}

它产生了以下输出:

size: 6
index: 0         -->    AAAaaa111$$$
index: 1         -->    AA
index: 2         -->    Aa
index: 3         -->
index: 4         -->
index: 5         -->    $
tests passed
Press any key to continue . . .

我想要达到的目的是告诉哪些群体无法匹配。例如,对于输入:SamplePassword1,只有第4组无法匹配,因为它不包含特殊字符。然后可以通知用户哪个特定要求/ s密码不符合。因此,SamplePassword1$将在每个组中匹配并传递。

使用单个正则表达式可以实现此任务,而不是针对每个要求使用单独的正则表达式吗?

我遇到了一个类似的问题here,但它在C#.NET中并使用了命名捕获组。

var re = new Regex("((?<a>a)|(?<b>b))");
var ma = re.Match("a");
Console.WriteLine("a in a: " + ma.Groups["a"].Success); //true
Console.WriteLine("b in a: " + ma.Groups["b"].Success); //false

1 个答案:

答案 0 :(得分:1)

override fun readMultipartCharacteristic(macAddress: String): Single<String> {
  val CERTIFICATE_TERMINATOR = 0x30.toByte()

  val device = bluetoothService.getBleDevice(macAddress)
  if (connectionObservable == null || !device.connectionState.equals(RxBleConnection.RxBleConnectionState.CONNECTED)) {
    connectionObservable = device.establishConnection(false, Timeout(30, TimeUnit.SECONDS))
  }

  val stop: PublishSubject<Unit> = PublishSubject.create()
  return connectionObservable!!
      .subscribeOn(Schedulers.io())
      .takeUntil(stop)
      .switchMap {
        it.readCharacteristic(UUID("my-uuid"))
            .repeat()
            .toObservable()
            .takeUntil(stop)
      }
      .collectInto(ByteArrayOutputStream(), { buffer, byteArray ->
        // Watch for the signal of the end of the stream
        if (byteArray.size == 1 && byteArray.get(0).equals(CERTIFICATE_TERMINATOR)) {
          stop.onComplete()
        } else {
          buffer.write(byteArray)
        }
      })
      .map {
        String(it.toByteArray())
      }
}

并查看std::regex rx("^((?=.*[a-z]))?((?=.*[A-Z]))?((?=.*[0-9]))?((?=.*[!-/:-@[-`{-~]))?(\\S){8,20}$"); Demo

那就是回忆the saying

  

有些人在面对问题时会想到,我知道,我会使用正则表达式。&#34;现在他们有两个问题。