【问题标题】:Regex for SwiftLint custom rule not matchingSwiftLint 自定义规则的正则表达式不匹配
【发布时间】:2018-07-13 13:24:19
【问题描述】:

我创建了正则表达式来确定一个类后面是否有一个空行。在 xcode 中搜索时,这非常有效。但是,swiftlint 似乎无法正常工作。

规则是:

custom_rules:
  space_after_class:
    name: "No Space After Class"
    message: "Empty line required after class declarations"
    regex: '(^(open|internal|private|public)*class\s(?!func).*\{$\n(?!^\s*$))'
    severity: error

这在 xcode/sublime/whatever 中搜索时可以正常工作,但由于某些原因,在 swiftlint 中会返回所有类声明(即使是那些带有新行的声明)

搜索示例:

规则示例(注意空白行 - 使用 ctrl+f 的同一个正则表达式找不到此行):

导致这种情况的 swiftlint 正则表达式有什么不同?

【问题讨论】:

    标签: swift xcode swiftlint


    【解决方案1】:

    您的 yml 文件需要正确格式化。尝试使用任何 yaml 验证器在线验证它。 似乎您的正则表达式需要引号 " 而不是 `。

    【讨论】:

      【解决方案2】:

      使用 SwiftLint 创建自定义规则很困难,因为没有验证级别,就像对“正常”规则的测试一样。试试AnyLint,它是专门为解决这个问题而编写的。它是用 Swift 编写的,但适用于任何基于正则表达式的语言。

      您的用例在 AnyLint 中将如下所示(我修复了您的正则表达式):

      // MARK: SpaceAfterClass
      try Lint.checkFileContents(
          checkInfo: "SpaceAfterClass: Empty line required after class declarations.",
          regex: #"^((?:open |internal |private |public )?(?:final )?class (?!func)[^\n]+\{\n)(?!\s*\n)"#,
          matchingExamples: ["class MyClass {\n  let", "public final class MyClass {\n  let"],
          nonMatchingExamples: ["class MyClass {\n\n  let", "public final class MyClass {\n\n  let"],
          includeFilters: [#".*\.swift"#]
      )
      

      使用 AnyLint,您甚至可以提供 autocorrectReplacement 进行自动更正,如下所示:

      // MARK: SpaceAfterClass
      try Lint.checkFileContents(
          checkInfo: ... // same parameters as above, plus:
          autoCorrectReplacement: "$1\n",
          autoCorrectExamples: [
              ["before": "class MyClass {\n  let", "class MyClass {\n  let"],
              ["before": "class MyClass {\n  let", "class MyClass {\n\n  let"],
          ]
      )
      

      我希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2016-07-22
        • 2016-09-09
        • 2021-04-07
        • 2018-01-10
        • 2015-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多