正则表达式返回空字符串

时间:2017-02-13 16:19:37

标签: html regex qt

我需要帮助使用正则表达式进行一些字符串替换。

任务:缩放生成的html字符串中的字体。我正在使用Qt,必须在Qt 4.8中工作。

我已经确定了一些正则表达式来分隔包含字体大小的部分,并对其进行了测试(https://regex101.com/r/Y0W13N/1) - 我不知道它是否正确或最佳,但测试网站似乎给了我正确的输出 - 但我的代码似乎没有匹配:

// get string between "<span style=\"" and "\">" (escaped quotes and backslashes)
QRegExp rx1("<span style=\"(?:=([^\\]]+))?(.*?);\">");
int pos = rx1.indexIn(text);
QStringList listSpans1 = rx1.capturedTexts();
qDebug() << listSpans1;                               // outputs ("", "", "") 

// get string between "<p style=\"" and "\">"
QRegExp rx2("<p style=\"(?:=([^\\]]+))?(.*?);\">");
pos = rx2.indexIn(text);
QStringList listSpans2 = rx2.capturedTexts();
qDebug() << listSpans2;                               // outputs ("", "", "") 

我正在测试的text

"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'MS Shell Dlg 2'; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Some Font'; font-size:15pt; color:#000000;">Te</span><span style=" font-family:'Some Font'; font-size:9pt; color:#000000;">xt</span></p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Some Font'; font-size:9pt; color:#000000;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Some Font'; font-size:9pt; color:#000000;"> B</span><span style=" font-family:'Some Font'; font-size:15pt; color:#000000;">ox</span></p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Some Font'; font-size:18pt; color:#000000;"></p></body></html>" 

我从qDebug得到空字符串 - 我不明白为什么假设测试网站显示正确的字符串,并且我似乎得到匹配?为什么要空......

(下一步是分开字体部分...确定字体大小...缩放它...替换回来......对于这么简单的操作似乎很复杂但我找不到更简单的方法)< / p>

我制作的正则表达式似乎在测试网站中有效,但它们在我的代码中不起作用,我不知道为什么,显然我没有正则表达式的经验。

请帮助我的正则表达式工作......谢谢

1 个答案:

答案 0 :(得分:1)

这里的要点是你不能在Qt *?中使用懒惰的+? / RegExp量词。

您可以使用rx1.setMinimal(true)并使用.*模式作为第1组模式来解决问题:

QRegExp rx1("<span style=\"(.*);\">");
rx1.setMinimal(true);

与第二个正则表达式相同:

QRegExp rx2("<p style=\"(.*);\">");
rx2.setMinimal(true);