我正在寻找拆分和删除QString。 QString中有几个单词,由以下符号中的一个或多个(×)分隔:
A-frame×N
A-line×NA
A-OK×A
A-pole×N
A-Z test×h
A/C×N
N
NA
A
N
h
N
src Qt C ++
QStringList verbs;
QFile inFile("example.txt");
if ( inFile.open( QIODevice::ReadOnly | QIODevice::Text ) ) {
QString line, value;
QTextStream stream( &inFile );
stream.setCodec("UTF-8");
for (int counter = 0; counter < 23; counter++) {
line = stream.readLine();
QRegExp sep("\w+$");
verbs << line.remove(sep);
}
qDebug() << verbs;
}
输出
("3-D×AN", "4-F×N", "4-H'er×N", "4-H×A", "A battery×h", "a bon march×v", "a cappella×Av", "a capriccio×h", "a datu×h", "a fortiori×v", "a gogo×Av", "A horizon×h", "a la carte×Av", "a la king×A", "a la mode×A", "a la×P", "A level×h", "a posteriori×A", "a priori×A", "a punta d'arco×h", "a quo×h", "a rivederci×h", "A supply×h")
答案 0 :(得分:0)
我试图根据提供的样本尽可能地概括模式:
[A-Z0-9][- \/]\b.+?\b×(?=\w{1,2}\b)
[A-Z0-9] // 1 char within the defined ranges
[- \/] // 1 char of defined options
\b.+?\b // 1 or more chars of anything, lazily matched, surrounded
// by word boundaries
× // an ascii character
(?= // looking ahead, assert the following matches
\w{1,2}\b // 1 or 2 word characters, then a word boundary
) // end of look ahead
如果使用模式运行替换为空白的函数,则可以获得所需的结果。如果要捕获结束字符,则需要对其进行分组(将前瞻变为捕获组(删除?=
))。
答案 1 :(得分:0)
首先,您需要使用命令设置区域设置 QTextCodec来:: setCodecForLocale(QTextCodec来:: codecForName( “UTF-8”)); 之后你应该打开文件。
当你在线阅读字符串时,你应该使用正则表达式 QRegExp(QString :: fromUtf8(“[×]”
检查以下代码:
int main()
{
QStringList verbs;
QFile inFile("example.txt");
if ( inFile.open( QIODevice::ReadOnly | QIODevice::Text ) )
{
QString line;
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
QTextStream stream( &inFile );
while(!stream.atEnd())
{
line = stream.readLine();
int i = line.indexOf(QRegExp(QString::fromUtf8("[×]")),0);
verbs << line.remove(0,i+1);
}
qDebug() << verbs;
}
}
〜