PyQt QSyntaxHighlighter字符串匹配正则表达式问题求助
Hey there! Let's tackle that regex issue you're facing with your PyQt text editor. The problem you're seeing—where everything after ("") gets marked as an error—happens because your regex rules are in the wrong order and the unclosed quote pattern is matching too broadly.
What's Wrong With the Current Regex?
Your current rules first check for unclosed quotes ("[^"\\]*(\\.[^"\\]*)*) before checking for properly closed ones. Since regex matches greedily, the unclosed pattern will latch onto characters even after a closing quote should have stopped it, leading to the over-highlighting you're seeing.
The Fix: Reorder Rules & Narrow the Unclosed Pattern
The key is to match properly closed strings first, then only target unclosed quotes that run to the end of the line (or document). Here's how to adjust your code:
STYLES = { 'string': format('magenta'), 'error': format('red', 'underline'), } rules += [ # First, match fully closed strings with proper escaping (r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES['string']), # Then, match unclosed quotes that end at the line (or document) end (r'"[^"\\]*(\\.[^"\\]*)*$', 0, STYLES['error']), # Add your other rules here... ]
Why This Works:
- Rule Order: By checking for closed strings first, we ensure valid quoted text gets marked as
stringbefore the error rule has a chance to interfere. - Line End Anchor (
$): The$in the unclosed quote pattern tells the regex to only match quotes that don't have a closing counterpart by the end of the line. This prevents it from swallowing up characters after a properly closed quote pair like("").
If you need to support multi-line unclosed strings (though that's less common in most syntaxes), you can tweak the unclosed pattern to match until the end of the document instead of just the line—just remove the $ and ensure your syntax highlighter handles multi-line ranges correctly.
内容的提问来源于stack exchange,提问作者Hunterx01

