2013-07-19 70 views
2

我有一個包含保留字列表的QString。我需要解析另一個字符串,搜索任何包含在第一個字詞中的字詞,並用'\'作爲前綴並修改這些字符。使用QRegExp替換QString中的單詞

例子:

QString reserved = "command1,command2,command3" 

QString a = "\command1 \command2command1 \command3 command2 sometext" 

parseString(a, reserved) = "<input com="command1"></input> \command2command1 <input com="command3"></input> command2 sometext" 

我知道我必須使用QRegExp,但我沒有找到如何使用QRegExp檢查,如果一個詞在我宣佈名單。你們能幫我嗎?

在此先感謝

+0

[QString :: contains](http://qt-project.org/doc/qt-5.0/qtcore/qstring.html#contains-5)和[QRegExp](http://qt-project.org /doc/qt-5.0/qtcore/qregexp.html) – Huy

回答

2

我的reservedWords列表分成QStringList然後遍歷每個保留字。然後,您預先輸入\字符(它需要在QString中轉義),並使用indexOf()函數查看輸入字符串中是否存在該保留字。

void parseString(QString input, QString reservedWords) 
{ 
    QStringList reservedWordsList = reserved.split(','); 
    foreach(QString reservedWord, reservedWordsList) 
    { 
     reservedWord = "\\" + reservedWord; 
     int indexOfReservedWord = input.indexOf(reservedWord); 
     if(indexOfReservedWord >= 0) 
     { 
      // Found match, do processing here 
     } 
    } 
} 
+0

請注意,您需要轉義\字符。 – 2013-07-19 17:28:01

+0

好的。我已經更新了答案。 –

+0

工作就像一個魅力,科裏!非常感謝! – Tyras

1

如果你想要做QRegEx這項工作,這裏是代碼:

QString reservedList("command1,command2,command3"); 

QString str = "\\command1 \\command2command1 \\command3 command2 sometext"; 

QString regString = reservedList; 
regString.prepend("(\\\\");  \\ To match the '\' character 
regString.replace(',', "|\\\\"); 
regString.append(")");   \\ The final regString: (\\\\command1|\\\\command2|\\\\command3) 
QRegExp regex(regString); 
int pos = 0; 

while ((pos = regex.indexIn(str, pos)) != -1) { 
    qDebug() << regex.cap(0); 
    pos += regex.matchedLength(); 
} 
0

我可以幫你用下面的代碼:

QString string1 = "a b c d e f g h i j k l m n o p q r s t u v w y z"; 
QRegExp regExp("(a|e|i|o|u|y)");//letters to be escaped with a backslash, brackets are used to capture the regular expressions in the current string 
string1.replace(regExp,"(\\1)");//Puts each letter a, e, i, o, u, y in brackets 
//string1=="(a) b c d (e) f g h (i) j k l m n (o) p q r s t (u) v w (y) z" 
string1 = "a b c d e f g h i j k l m n o p q r s t u v w y z"; 
QRegExp regExp2("a|e|i|o|u|y"); 
string1.replace(regExp2,"(\\1)");//Replace each letter a, e, i, o, u, y by the string (\1) 
//string1=="(\1) b c d (\1) f g h (\1) j k l m n (\1) p q r s t (\1) v w (\1) z" 

在您的情況:

QString reserved = "command1,command2,command3"; 
QString copyOfReserved = reserved; 
copyOfReserved.replace(",","|"); 
//copyOfReserved == "command1|command2|command3" 
copyOfReserved = "\\b("+copyOfReserved+")\\b"); 
//copyOfReserved == "\b(command1|command2|command3)\b" 
QString a = "\\command1 \\command2command1 \\command3 command2 sometext"; 
QString b = a; 
b.replace(QRegExp("\\\\(" + copyOfReserved + ")"),"<input com=\"\\1\"></input>"); 
//b == "<input com="command1"></input> \command2command1 <input com="command3"></input> command2 sometext" 

我希望我幫你。