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

发布于 2025-02-03 06:15:55 字数 200 浏览 1 评论 0原文

我想为无与伦比的字符串返回一个布尔值,

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

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

I want to return a bool value for the unmatched string

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

It returns false every time no matter what string is passed. How can I match the same values?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

江南月 2025-02-10 06:15:55

不确定您要准确地做什么,但是您可以在输入字符串上迭代并在任何一个不匹配给定模式时做某事。

请注意,我正在使用std :: copy_if(C ++ 17),但您不需要。

[demo]

#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"]

Not sure what you want to do exactly but you could iterate over the input strings and do something when any of them doesn't match a given pattern.

Notice I'm using std::copy_if (C++17) below, but you shouldn't need to.

[Demo]

#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"]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文