1

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
bennyyy999
  • 80
  • 1
  • 5
  • is the is/has the start of the line? – user253751 May 17 '23 at 18:43
  • Does this answer your question? [Understanding positive and negative lookaheads](https://stackoverflow.com/questions/27691225/understanding-positive-and-negative-lookaheads) – njzk2 May 17 '23 at 18:45
  • 1
    why do you require capital at start of your regex but your sample is lowercase? – jhnc May 17 '23 at 19:06
  • @jhnc I actually dont know, but you are right, thats an error from my side – bennyyy999 May 17 '23 at 19:13
  • one ugly way is you can write ([^ih]|i[^s]|h[^a]|ha[^s]) to match some character that aren't is or has – user253751 May 17 '23 at 19:13
  • since you appear not to actually want to match at start/end of line, nor to require uppercase, perhaps: `\b(?!is|has)[A-Za-z]+: Bool\b` – jhnc May 17 '23 at 19:54

2 Answers2

2

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

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

Jeff Y
  • 2,437
  • 1
  • 11
  • 18