Qt中,编写一个函数来支持后行断言

在Qt中,由于QRegExpQRegularExpression都不支持后行断言正则表达式,我们需要编写一个自定义函数来手动处理这个逻辑。以下是函数,它接受一个字符串,并检查该字符串是否包含tr("文"),但确保它前面没有Lang::Tr(

#include <QString>
#include <QDebug>

bool containsTrWithoutLangTr(const QString &input) {
    // 定义要查找的字符串
    QString trString = "tr(\"文\")";
    QString langTrString = "Lang::Tr(";

    // 遍历输入字符串
    int index = 0;
    while (index < input.length()) {
        // 检查当前位置是否包含 Lang::Tr(
        int langTrIndex = input.indexOf(langTrString, index);
        if (langTrIndex != -1) {
            // 找到了 Lang::Tr(,现在查找它的结束右括号
            int closingParenthesisIndex = input.indexOf(')', langTrIndex + langTrString.length());
            if (closingParenthesisIndex != -1) {
                // 跳过了 Lang::Tr( ... ) 区域
                index = closingParenthesisIndex + 1;
                continue;
            } else {
                // 没有找到结束的右括号,这意味着 Lang::Tr( 后面的内容都是无效的,返回 false
                return false;
            }
        }

        // 检查当前位置是否包含 tr("文")
        int trIndex = input.indexOf(trString, index);
        if (trIndex != -1) {
            // 找到了 tr("文"),并且它前面没有 Lang::Tr(,返回 true
            return true;
        }

        // 没有找到 tr("文"),继续搜索
        index++;
    }

    // 遍历完整个字符串,没有找到 tr("文"),返回 false
    return false;
}

int main() {
    QString test1 = "55566tr(\"文\")11122";
    QString test2 = "55566Lang::Tr(tr(\"文\"),\"100\")11122";
    QString test3 = "some text tr(\"文\") more text";
    QString test4 = "some text Lang::Tr(something) tr(\"文\")";
    QString test5 = "Lang::Tr(other) some text tr(\"文\")";

    qDebug() << containsTrWithoutLangTr(test1); // Should return true
    qDebug() << containsTrWithoutLangTr(test2); // Should return false
    qDebug() << containsTrWithoutLangTr(test3); // Should return true
    qDebug() << containsTrWithoutLangTr(test4); // Should return false
    qDebug() << containsTrWithoutLangTr(test5); // Should return true (since tr("文") is not immediately following Lang::Tr())

    return 0;
}

在这个函数中,我们使用了一个循环来遍历输入字符串。在每次迭代中,我们首先检查当前位置是否包含Lang::Tr(。如果找到了,我们就查找它的结束右括号,并跳过这个区域。如果没有找到结束的右括号,这意味着Lang::Tr(后面的内容都是无效的,我们直接返回false

如果我们没有找到Lang::Tr(,我们就检查当前位置是否包含tr("文")。如果找到了,并且它前面没有Lang::Tr(,我们就返回true

如果我们遍历完整个字符串都没有找到tr("文"),或者每次找到的tr("文")前面都有Lang::Tr(,我们就返回false

这个函数应该能够满足你的需求,即检查字符串中是否包含tr("文"),但确保它前面没有Lang::Tr(

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liwension

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值