[英]How to handle pure regex results in Qt application?
我有C ++正则表达式对象
smatch matches;
regex pattern("key(\\d{3}\\w{1})");
通过regex_search()
函数,我正在成功搜索我的模式。 结果,我执行了工作命令: cout << matches[1]; // sub_match as output.
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();
}
希望能有所帮助。
@phyatt谢谢!
这样的代码可以正常工作:
QTextEdit *textEdit = new QTextEdit;
QString outputString1 = QString::fromStdString(matches[1]);
textEdit->setText(QString("%1:").arg(outputString1));
textEdit->show();
每次满足正则表达式条件时,都会在新窗口中显示文本:例如key123c
虽然,我应该如何继续在不是每次在新窗口中而是在QTextEdit窗口(通过Qt Designer设置)中看到此结果? 设置上述代码的函数位于构造函数之外,因此仅是基本的:void function_from_where_results_somes();
我创建了另一个问题: 从函数访问QTextEdit小部件
phyatt,您能同时解决这个问题吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.