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

65 views Asked by At

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
2

There are 2 answers

5
Martin del Necesario On BEST ANSWER

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
0
Jeff Y On

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