我正在尝试为 linter 构建一个(多行)模式,以捕获以下情况:
- 有一个
Text(
声明 - 这不是后跟
.appFont(
声明... - ...在下一次出现
}
(函数结束)或Text(
(另一个文本声明...)之前
经过几个小时的 regex101(并咨询 gpt...)我得到了这些 2:
Text\([\s\S]*?\)[\s\S]*?(?!\.appFont)
这只是捕获 .appFont
之前的部分,但我希望如果找到 .appFont
则整个捕获失败...
Text\([\s\S]*?\)[\s]*?(?!appFont)[\s\S]\}
这只是捕获了所有内容,完全忽略了 appFont
的情况......
在以下示例中,仅应捕获第二种情况:
Text("blah")
.appFont(.body)
}
Text("blah")
}
Text(
"blah"
)
.appFont(.blah)
}
我尝试阅读有关负向前瞻的内容,但我认为我仍然以某种方式错误地使用它,或者以某种方式导致它在我添加 [\s\S]
时被忽略?
最佳答案
使用 negated character class与负面一起 lookahead .
Text\([^)]*\)(?:(?!\.appFont)[^}])*}
See this demo at regex101 - 有点类似于tempered greedy token .
Text
\([^)]*\)
(
接下来是 any amount的non- )
否定类别直到下一次收盘 )
(?:(?!\.appFont)[^}])*}
(?:
non capturing group )
重复*
any amount次,包含:(?!\.appFont)
否定。 lookahead检查每个 non- }
前面if 子串 \.appFont
不领先 - 消耗成功时每个匹配字符最多 }
或者在关闭 )
后仅使用一次前瞻断言.
Text\([^)]*\)(?![^}]*?\.appFont)[^}]*}
Another demo at regex101 - 这里甚至可能更有效率。
Text
\([^)]*\)
(
接下来是 any amount的non- )
直到下一次收盘)
(?![^}]*?\.appFont)
[^}]*?\.appFont
不领先在哪里[^}]*?
匹配lazily any amount的non- }
直到子字符串 \.appFont
[^}]*}
}
高达 }
关于正则表达式在特定位置的模式中找不到子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76035642/