只匹配特定字符串,前提是整行不包含特定术语。

huangapple go评论65阅读模式
英文:

Match a specific string only if the entire line doesn't include a specific term

问题

我想要使用正则表达式来匹配所有变量 nationFile 的实例,除非此变量包含在导入语句内。实质上,只匹配字符串 nationFile,只要整行开头不包含 import。

我从这个正则表达式开始,但没有成功。

(?<!import)nationFile

这不起作用,因为 import 和 nationFile 之间可能会有其他文本,但是我尝试过的任何方法似乎都将此文本包括在匹配的中间,这是我不想要的。

这个解决方案也不起作用,因为回顾断需要具有固定的长度。

(?<!import.*)nationFile
英文:

I'd like to match all instances of the variable nationFile using a Regex, except when this variable is contained within an import statement. Essentially matching ONLY the string nationFile as long as the entire line does not contain import at the beginning.

I began with this regex but had no luck.

(?&lt;!import)nationFile

This doesn't work because there might be other text in between import and nationFile, however any attempt I've made seems to include this text in the middle as part of the match, which I do not want.

This solution doesn't work either as lookbehinds need to have a fixed length.

(?&lt;!import.*)nationFile

答案1

得分: 0

这里有一个解决方案可能不太优雅,但应该有效。

假设你想要将 nationFile 替换为 somethingElse

如果你在使用VSCode,就无法在非固定宽度情况下使用lookbehind。

但你可以使用这个正则表达式来捕获整行:

^((?:(?!import).)*?)nationFile

这确保了在从行的开头遇到 nationFile 之前没有 import,然后用以下内容替换它:

$1somethingElse

$1 是指从行开头到 nationFile 之间的任何内容。所以你可以保留在 somethingElse 之前的一切。

但你可能需要多次搜索和替换,因为它每次只能捕获一次 nationFile,直到没有匹配项为止。

英文:

Here's a solution might not be very elegant, but it should work.

Let's say you want to replace nationFile with somethingElse

If you're using VSCode, it is not possible to use lookbehind with non-fixed width.

But you could capture the whole line using this regex:

^((?:(?!import).)*?)nationFile

This ensures there's no import before encountering nationFile from the beginning of the line, then replace it with

$1somethingElse

The $1 refers anything between the beginning of the line and nationFile. So you could preserve everything before somethingElse.

But you might want to search and replace multiple times since it can only capture one instance of nationFile each line at a time, until there are no matches left.

huangapple
  • 本文由 发表于 2023年7月20日 09:27:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76726127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定