c++ - 如何在 Qt 应用程序中处理纯正则表达式结果?

标签 c++ regex qt c++11

我有 C++ 正则表达式对象

smatch matches;
regex pattern("key(\\d{3}\\w{1})"); 

通过 regex_search()功能 我正在成功搜索我的模式。 结果我执行了工作命令:cout << matches[1]; // sub_match as output.

在我的 Qt 应用程序中,我想显示结果是 QTextEdit或任何其他小部件。

我试过:

QTextEdit *textEdit = new QTextEdit(); 
textEdit->setText(QString("%1:").arg(matches[1]));

但结果是:

error C2664: 'QString QString::arg(qlonglong,int,int,QChar) const' : cannot convert parameter 1 from 'const std::sub_match<_BidIt>' to 'qlonglong'
1>          with
1>          [
1>              _BidIt=std::_String_const_iterator<std::_String_val<std::_Simple_types<char>>>
1>          ]
1>          No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

有人可以提供任何想法来处理这个问题吗?我知道有 QRegExp类,但它有类似的regex_search()吗?功能 ?我更喜欢使用我当前代码的解决方案。

提前致谢!

最佳答案

要解决您看到的错误,您需要正确地将 std::string 转换为 QString

http://www.cplusplus.com/reference/regex/smatch/

https://stackoverflow.com/a/1814214/999943

如果您对使用 QRegEx 感兴趣,我已经发布了一些关于它们的答案。

https://stackoverflow.com/search?q=user%3A999943+qregex

关于 QRegEx 的文档也不错,但是一些关于如何很好地使用它的细节隐藏在一些函数文档中。

http://qt-project.org/doc/qt-5/QRegExp.html

示例代码

std::regex pattern("key(\\d{3}\\w{1})");
std::smatch matches;
std::string str = "key123a key123b";

if (std::regex_search(str, matches, pattern))
{
    qDebug() << "Match";

    for (int i = 0; i< matches.size(); i++)
    {
//            std::cout << "  submatch " << matches[i] << std::endl;
        QString outputString = QString::fromStdString(matches[i]);
        qDebug() << outputString;
    }
}
else
    qDebug() << "No match";

还有一个只有 Qt 东西的解决方案,基于

http://qt-project.org/doc/qt-5/qregexp.html#indexIn

QRegExp rx("key(\\d{3}\\w{1})");
QString str = "key123a key123b";
int count = 0;
int pos = 0;
while ((pos = rx.indexIn(str, pos)) != -1) {
    ++count;
    pos += rx.matchedLength();
    qDebug() << rx.capturedTexts();
}

希望对您有所帮助。

关于c++ - 如何在 Qt 应用程序中处理纯正则表达式结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21369818/

相关文章:

javascript - 用于确定字母数字代码是否在范围内的正则表达式

c++ - 为 Arduino 创建一个库

c++ - SDL2 未定义的函数引用

c++ - 段错误,当使用 cmake 编译时没有 cout

c++ - 使用 C++11 在 DirectX 11.2 应用程序中测量 3D 模型的体积

c++ - 如何在一个qt qml窗口中运行并显示4个可执行文件?

regex - 找到正则表达式的补码

regex - 转换为数字 : simplify 2 calls of gsub to one

c++ - Asio C++ 库 : asio/detail/config. hpp:没有这样的文件或目录

c++ - gthread.h 数组大小为负