Q字符串只替换第一个出现的项

QString replace only first occurrence

本文关键字:第一个 字符串 替换      更新时间:2023-10-16

在QString中,是否有一种简单的方法可以将某个子字符串的第一次出现替换为其他子字符串?它可以在任何位置。

你可以试试这个:

QString str("this is a string"); // The initial string.
QString subStr("is"); // String to replace.
QString newStr("at"); // Replacement string.
str.replace(str.indexOf(subStr), subStr.size(), newStr);

结果字符串为:

在字符串

对于您想要的操作,没有方便的方法。但是,您可以使用以下两种方法来构建您的自定义操作:

int QString::indexOf(const QString&str,int from=0,Qt::CaseSensitivity cs=Qt:)const

返回此字符串中第一个字符串str的索引位置,从中的索引位置向前搜索。如果找不到str,则返回-1。

如果cs是Qt::CaseSensitive(默认值),则搜索区分大小写;否则,搜索不区分大小写。

QString&QString::replace(int position,int n,const QString&after)

将从索引位置开始的n个字符替换为后面的字符串,并返回对此字符串的引用。

注意:如果指定的位置索引在字符串内,但位置+n超出字符串范围,则n将被调整为停止在字符串的末尾。

现在,将所有这些付诸实践,您可以编写如下内容:

main.cpp

#include <QString>
#include <QDebug>
int main()
{
QString initialString = QLatin1String("foo bar baz");
QString fooString = QLatin1String("foo");
initialString.replace(initialString.indexOf(fooString),
fooString.size(), QLatin1String("stuff"));
qDebug() << initialString;
return 0;
}

main.pro

TEMPLATE = app                                         
TARGET = main                                              
QT = core                                              
SOURCES += main.cpp

构建并运行

qmake && make && ./main

输出

"stuff bar baz" 

这几乎是QString::replace(QRegularExpression,…)的方法。由于字面反斜杠可能是替换模式的一部分,因此需要以不同的方式捕获这些反斜杠。请注意,实际的替换是从右到左进行的,以保持向左偏移的有效性。可以更紧凑地表达,但在这种形式下更容易调试。

QRegularExpression regex = QRegularExpression(regex_pattern);
if (regex.isValid() and
(regex_pattern.length() > 0)) {
QRegularExpressionMatchIterator regex_iterator =
regex.globalMatch(target_text, Apply_Target_Offset,
QRegularExpression::PartialPreferCompleteMatch);
if (regex_iterator.hasNext()) {
// At least one found
QRegularExpressionMatch match = regex_iterator.next();
if (match.hasMatch() and (not match.hasPartialMatch())) {
// This is the first match, and it's complete
int match_begin = match.capturedStart();
int match_end = match.capturedEnd();
int match_length = match.capturedLength();
QStringList captured;
const int capture_groups_count = regex.captureCount() + 1;
for (int capture_group_idx = 0; capture_group_idx < capture_groups_count; ++capture_group_idx) {
captured.append(match.captured(capture_group_idx));
}
QString replace_pattern = Apply_Replace_Pattern->toPlainText();
QString replace_text = replace_pattern;
QList<QRegularExpressionMatch> replace_pattern_match_list;
QRegularExpression replace_pattern_regex = QRegularExpression("(?:\\\\)+|(?:\\(\d+))");
if (replace_pattern_regex.isValid()) {
QRegularExpressionMatchIterator replace_pattern_regex_iterator =
replace_pattern_regex.globalMatch(replace_pattern);
while (replace_pattern_regex_iterator.hasNext()) {
QRegularExpressionMatch replace_pattern_match = replace_pattern_regex_iterator.next();
bool no_error;
replace_pattern_match.captured().right(1).toInt(&no_error);
// Only accept backreferences w/ numbers
if (no_error) replace_pattern_match_list.append(replace_pattern_match);
}
while (replace_pattern_match_list.count() > 0) {
QRegularExpressionMatch replace_pattern_match = replace_pattern_match_list.takeLast();
int cap_idx = replace_pattern_match.captured(1).toInt();
if (cap_idx < captured.count()) {
replace_text.replace(replace_pattern_match.capturedStart(),
(replace_pattern_match.capturedEnd() -
replace_pattern_match.capturedStart()),
captured[cap_idx]);
}
}
// Render '' characters properly
replace_text.replace("\\", "\");
}
target_text.replace(match_begin, (match_end - match_begin), replace_text);
}
}
}
//------------------------------------------------------------------
QString & replace_first(QString &io_haystack, const QString & sub_str, const QString & new_str)
{
io_haystack.replace(io_haystack.indexOf(sub_str), sub_str.size(), new_str);
return io_haystack;
} // replace_first
//------------------------------------------------------------------
QString & replace_first(QString &io_haystack, const QRegularExpression & sub_regx, const QString & new_str)
{
QRegularExpressionMatch match;
match = sub_regx.match(io_haystack);
if (match.hasMatch()) {
QString sub_str = match.captured(0);
io_haystack.replace(io_haystack.indexOf(sub_str), sub_str.size(), new_str);
}
return io_haystack;
} // replace_first