Search code examples
swiftregexregex-negationswiftlint

Match "com.project.name" but not when it contains something else


I have the following code:

var i = "test"

and

var i = "com.project.name.test"

print("something else")
fatalError("some error")

I have a regex:

"((?!com\.project\.name).)*"

to match any string that does NOT contain "com.project.name".

However, I want to modify it to still have the above condition but not if the line contains print\(.*?\) and fatalError\(.*?\).

Why do I want to do this? Because I can only use regex for SwiftLint custom rules and right now my regex is greedy and matches every single string in the project that the developers forgot to localize..

What I've tried:

"((?!com\\.project\\.name).)*(?!print)(?!fatalError)"

but it does not work and instead matches the same as the original expression.


Solution

  • You may use this regex with a negative lookahead assertions:

    ^(?!.*(?:com\.project\.name|print\(|fatalError\()).*
    

    RegEx Demo

    This negative lookahead assertion uses alternations to fail the match on 3 different matches anywhere in the input:

    1. com\.project\.name
    2. print\(
    3. fatalError\(