I'm using Swiftlint to enforce some practices in our codebase. I want to add a custom rule that makes sure a {
always appears after a newline. I thought I knew regexes, but can't seem to figure it out. I just check if a line contains any characters other than whitespace before the {
. It is allowed to have stuff after the {
.
What I have now:
invalid_open_brace:
name: "Open brace should start on its own line"
regex: "(\S+.*\{)"
message: "Open brace should start on its own line"
severity: warning
Here are some example strings that should and should not match:
// NO MATCH
else if let var1 = var1 as? String, !var1.isEmpty
{
//NO MATCH
class Person
{
// MATCH
int()
{
}
// NO MATCH
function()
{
}
}
// MATCH
function() {
}
Your (\S+.*\{)
regex matches any char that is not whitespace (one or more reptitions - \S+
), then any char other than linebreak (including non-whitespaces - here is the root cause of your issue), and {
.
You may use
\S[ \t]+\{
See the regex demo.
Details:
\S
- any non-whitespace char[ \t]+
- one or more (+
) horizontal whitesapces (can be replaced with [\t\p{Zs}]+
where \p{Zs}
matches all horizontal Unicode whitespace without a tab).\{
- a literal {
symbol.