Reputation: 2846
I have a regular expression: (struct|class|protocol)\s(?!(func|DB|DC|DM))[^\n\r]+\{
that basically is matching any class
, struct
, or protocol
definition that is not prefixed with DC, DB, or DM. This works fine, but we want it to match top level declarations only. To accomplish this, I'm trying to only match declarations that include no white space before them, i.e.
class ThisClassMatches { // this class triggers a match
struct ThisStructDoesNotMatch { // This struct shouldn't trigger a match
}
}
I've tried a lot of combinations of [^\s]
, ([^\s]|[^\S])
, ^[^\s]...regex...$
, all to no avail. I'm not sure what the appropriate regex would be to trigger a match only when there's no white space (i.e., the first character on the line is a letter)
P.S. I'm using swiftlint on an iOS project to enforce naming parameters, if that makes any difference in the answer (it shouldn't)
Upvotes: 0
Views: 76
Reputation: 23880
You can use a leading anchor, ^
and that will require the string/line (depending on where the regex is using and modifiers) start with the next string. For example:
^(struct|class|protocol)\s(?!(func|DB|DC|DM))[^\n\r]+\{
Demo: https://regex101.com/r/4sL09E/1 (with no modifier)
https://regex101.com/r/4sL09E/2 (with modifier)
Upvotes: 2