【问题标题】:Matching entire string in gtksourceview匹配 gtksourceview 中的整个字符串
【发布时间】:2025-12-16 05:00:02
【问题描述】:

使用这个简短的 XML sn-p 在 gtksourceview 中定义字符串:

<context id="string" style-ref="string" end-at-line-end="true">
    <start>"</start>
    <end>"</end>
    <include>
        <context id="special-string" style-ref="special">
            <match>(foo|bar)</match>
        </context>
        <context ref="def:line-continue"/>
    </include>
</context>

这会突出显示字符串中的任何“foo”或“bar”实例。假设我想在它们是整个字符串时突出显示这两个字符,以便“foo”突出显示中间三个字符,但根本不突出显示“foobar”。这在 gtksourceview 中可行吗?

我尝试使用锚点 ^...$ 和lookahead/lookbehind (?&lt;=") / (?=") 但前者不起作用,后者完全破坏了语法荧光笔。

【问题讨论】:

  • 您正在寻找的是负前瞻吗? foo(?!bar) ?请参阅此正则表达式示例:regex101.com/r/eL9tK2/1
  • @Jan:不,积极的前瞻/后瞻,而不是消极的。我想匹配“foo”和“bar”,但不匹配“xxfooxx”等。但即使 gtksourceview 声称使用 PCRE,它似乎也被这些表达方式扼杀了。 (这里的引号是字符串的一部分:三个字母 foo 不会被突出显示,只有在被引号包围时才会突出显示。)
  • 我会想到单词边界:regex101.com/r/eL9tK2/2(参见更新的示例)。
  • @Jan:不,因为不应突出显示“X foo”。 Foo 仅在前后加引号时突出显示。 (在我的实际应用中,有大量的替代品,不只是 foo 和 bar,但这应该没什么大不了的。)
  • 这个很简单:regex101.com/r/eL9tK2/3

标签: regex string syntax-highlighting pcre gtksourceview


【解决方案1】:

似乎没有办法在子上下文中匹配父上下文的开头(或结尾)。但是,如果您将 special-string 定义为*上下文并将其包含在主语言上下文中的 string 之前,它将起作用:

<context id="special-string" style-ref="string">
    <match>"(foo|bar)"</match>
    <include>
        <context sub-pattern="1" style-ref="special"/>
    </include>
</context>

<context id="string" style-ref="string" end-at-line-end="true">
    <start>"</start>
    <end>"</end>
</context>

【讨论】: