Important: Please read the Qt Code of Conduct -

Replacing words in a string

  • Hi
    If I have a string -
    QString s = "Some text MyWord some more text MyWordAgain"
    Now I want to replace occurrences of 'MyWord' but ONLY where that is the whole word, so that in the above example 'MyWordAgain' would not be replaced.
    I tried
    but obviously it replaced both occurrences.
    How can I achieve this?


  • -use QString::indexOf to find the index of the first occurrence
    -use QString & QString::replace ( int position, int n, const QString & after )

  • Lifetime Qt Champion


    You can also use QRegularExpression/QRegExp depending whether you're using Qt 5 or Qt 4

  • Hi
    I tried with regular expressions but cannot get a match
    QRegualrExpression regExp("\bMyWord");
    Can anyone suggest what is wrong with my regular expression?


  • Try it ...
    QString str="Some text MyWord some more text MyWordAgain";
    s.replace(" MyWord "," AnotherWord "); //both strings having one character spaces before and after .

  • Thanks all

  • bq. Try it …
    QString str=“Some text MyWord some more text MyWordAgain”;
    s.replace(” MyWord “,” AnotherWord “); //both strings having one character spaces before and after .

    this is a particular case ... what if you'd want to replace substring within a word or the substring to replace is at the beginning of the string(without leading space character)?

  • Ok So my problem is not solved
    I need to replace all occurrences of a word in a string
    So I created a QRegularExpression -
    QRegualrExpression regexp("\bWord");
    QString s = "this Word is to be replaced and this Word but not this Wordaaaa";
    This has the effect of setting s to
    this NewWord is to be replaced and the NewWord but not this NewWordaaaa
    How can I stop the last substitution being made?

    Thanks again

  • try this:

    @QRegualrExpression regexp("\bWord\b");@

Log in to reply