繁体   English   中英

使用正则表达式查找不匹配的字符串

[英]To find the string that are not matching using regex pattern

我想为不匹配的字符串返回一个布尔值

QRegExp rx("(?!test)");
bool unmatched = rx.exactMatch("txt"); false
if(rx.isValid()){
  return unmatched;
}

无论传递什么字符串,它每次都返回 false。 如何匹配相同的值?

不确定您到底想做什么,但是您可以遍历输入字符串并在其中任何一个与给定模式不匹配时执行某些操作。

请注意,我在下面使用std::copy_if (C++17),但您不需要这样做。

[演示]

#include <algorithm>  // copy_if
#include <fmt/ranges.h>
#include <iostream>  // cin
#include <iterator>  // back_inserter, istream_iterator
#include <regex>  // regex_search
#include <string>
#include <vector>

int main() {
    std::regex pattern("test");
    std::vector<std::string> v{};
    std::copy_if(
        std::istream_iterator<std::string>{std::cin}, {},
        std::back_inserter(v), 
        [&pattern](const std::string& s) {
            return not std::regex_search(s, pattern);
    });
    fmt::print("{}", v);
}

// Input:
//
//   blah
//   foo1 test
//   foo2test
//   testfoo3
//   test

// Output:
//
//   ["blah", "foo1"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM