multiple negative look around working in regex tester, failing in SwiftLint build

71 Views Asked by At

Here is a link to the regex tester.

It successfully matches the class Second { and the class MyClass {. In the tester, but when I bring the same rule into my swiftlint.yml it doesn't match the same classes in my project.

  unnecessary_class:
    name: "Class doesn't need to exist"
    regex: 'class(?!(.*XC)|(.*UI)|(.*Model)|(.*model))'
    message: "A new class should have a reason to exist, if it isn't a model, codable, UI subclass, nor a View conformer, then there are alternative approaches instead of creating a new class."
    severity: error
1

There are 1 best solutions below

1
Blazej SLEBODA On

The observed difference is related to the default regex options in SwiftLint which include anchorsMatchLines and dotMatchesLineSeparators. The latter option is what causes the difference between your regex tester and the results given by SwiftLint.

To solve the problem, you can disable dotMatchesLineSeparators by adding the (?-s) syntax to your regex pattern in SwiftLint config. This will override the default options and disable the dotMatchesLineSeparators option for that specific rule.

Here is an example of how you can modify the unnecessary_class rule in your SwiftLint config to include (?-s) and disable dotMatchesLineSeparators:

unnecessary_class:
  name: "Class doesn't need to exist"
  regex: '(?-s)class(?!(.*XC)|(.*UI)|(.*Model)|(.*model))'
  message: "A new class should have a reason to exist, if it isn't a model, codable, UI subclass, nor a View conformer, then there are alternative approaches instead of creating a new class."
  severity: error