正则表达式,不包含 is|has 前缀但以 : 结尾:Bool

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

Regex that doesn't contain is|has prefix but ends with : Bool

问题

以下是翻译好的内容:

抱歉,我不得不问一下,虽然有其他答案,但我不能理解并适应我的问题。

所以我正在编写一个自定义的SwiftLint规则,应该检查:

  • 没有以ishas前缀开头
  • : Bool后缀结尾

我的当前正则表达式如下,但它显示了包含is或has的内容,但我希望它显示不包含它们的内容

(is|has)[A-Z][A-Za-z]*(: Bool)

我也尝试了这个,但它不会显示任何消息,所以我猜它是错误的:

^(?!is|has)[A-Z][A-Za-z]*: Bool$

那么,正确的正则表达式是什么?

编辑:
应该是这样的:

`isHello: Bool` -> 无需警告
hello: Bool -> 应该提醒我,缺少is或has前缀

编辑2:

@State private var showActionSheet: Bool = false -> 应该给我一个警告
@State private var hasStartWorkout: Bool = false -> 不应该给我警告
英文:

Sorry that I have to ask that, with all the other answers around, but I can't get my head around to think and adapt to my problem.

So I'm writing a custom SwiftLint rule that should check:

  • does not have is or has prefix
  • does have : Bool suffix

My current Regex looks like this, but it shows me the stuff that contains is or has, but I want it to show me things that don't have it

(is|has)[A-Z][A-Za-z]*(: Bool)

I also tried this, but it won't show me any message, so I guess it's wrong:

^(?!is|has)[A-Z][A-Za-z]*: Bool$

So, what's the correct Regex?


EDIT:
How it should be:

`isHello: Bool` -> nothing
hello: Bool -> should alarm me, missing is or has prefix

EDIT 2:

@State private var showActionSheet: Bool = false -> should give me a warning
@State private var hasStartWorkout: Bool = false -> should not give me a warning

答案1

得分: 2

你的问题在于,在负向先行断言成功的情况下,以下正则表达式部分不匹配:“^(?!is|has)[A-Z][A-Za-z]*: Bool$”。在你的示例中,不以is/has开头的行(“hello”)以小写字符开头。因此,你需要将该部分移到负向先行断言内,就像这个正则表达式中的方式:

(^| )(?!has[A-Z]|is[A-Z])[A-Za-z]+: Bool
英文:

Your problem is, that in a successful case of the negative lookahead the following regex part is not matching: "^(?!is|has)[A-Z][A-Za-z]*: Bool$". In your example, the line that doesn't start with is/has ("hello") starts with a lower character. So you have to move said part inside of the negative lookahead like in this regex:

(^| )(?!has[A-Z]|is[A-Z])[A-Za-z]+: Bool

答案2

得分: 0

抱歉,你需要的是这样的代码:

/^([^ih]|i[^s]|h[^a]|ha[^s])[A-Za-z]*: Bool$/gm

更丑陋的是,如果你需要强制在“is”或“has”之后是大写字母。

只有当你需要纯正则表达式时才需要这样。如果你可以使用类似grep -v的东西,生活会更简单…

针对你的“编辑2”进行更新:
/( |^)([^ih]|i[^s]|h[^a]|ha[^s])[A-Za-z]*: Bool/gm

英文:

Unfortunately, you need something rather ugly like this:

/^([^ih]|i[^s]|h[^a]|ha[^s])[A-Za-z]*: Bool$/gm

And it gets even uglier if you need to enforce an uppercase after the “is” or “has”.

That’s only if you need pure regex. If you can use something like grep -v, life is simpler…

Updated for your “Edit 2”:
/( |^)([^ih]|i[^s]|h[^a]|ha[^s])[A-Za-z]*: Bool/gm

huangapple
  • 本文由 发表于 2023年5月18日 02:40:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275273.html
匿名

发表评论

匿名网友

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

确定