我想突出显示出现在字符串中的某个单词,但这个单词可以更改,并可以以字母数字字符以及'#','$',' - '和'_' 。在Python中,如何匹配可能以#字符开头的QRegExp字符串?
现在我有这样的:
pattern = "\\b" + QRegExp.escape(word) + "\\b"
regex = QRegExp(pattern)
index = regex.indexIn(self.edit_box.toPlainText(), pos)
然后我突出基于所述起始索引和通过移动光标以一定的背景颜色的所选择的字的长度。
的问题存在于以下情况:
sentence = "#ff0000 hey this is a test #ff0000"
word = "#ff0000"
pattern = "\\b" + QRegExp.escape(word) + "\\b"
regex = QRegExp(pattern)
pos = 0
index = regex.indexIn(sentence, pos)
while (index != -1):
print 'this is entered'
print 'done!'
output: done!
看来,以“#”可能只是治疗正则表达式模式只是一个评论,甚至QRegExp.escape()。
单词边界是单词字符(字母,数字,下划线)与非单词字符(其他所有内容)或字符串的开始/结尾之间的边界。空格和#都是非单词字符。您可以使用lookarounds构建自定义边界,例如'(?<!\ w)#ff0000(?!\ w)'。 –
我不认为[QRegExp](http://doc.qt.io/qt-4.8/qregexp.html)支持lookbehind。我猜''pattern =“(?:^ | \\ W)(”+ QRegExp.escape(word)+“)(?!\\ w)”'会在这里做,只是应该采用组1的索引, 'regex.pos(1)'。 –
@WiktorStribiżew似乎是如此,那么使用替代和重新安排索引的替代方案已经在您的答案中。 –