I'm trying to make a regex that matches a semantic version (SemVer) 2.0.0. This is my first try:
^(?'major'\d+)\.(?'minor'\d+)(?:\.(?'patch'\d+))?(?:-(?'preRelease'(?:(?'preReleaseId'[0-9A-Za-z-]+)\.?)+))?(?:\+(?'build'(?:(?'buildId'[0-9A-Za-z-]+)\.?)+))?$
This passes my smoke tests, but when I try to actually make it a NSRegularExpression
, I get this:
Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=2048 "The value “^(?'major'\d+)\.(?'minor'\d+)(?:\.(?'patch'\d+))?(?:-(?'preRelease'(?:(?'preReleaseId'[0-9A-Za-z-]+)\.?)+))?(?:\+(?'build'(?:(?'buildId'[0-9A-Za-z-]+)\.?)+))?$” is invalid." UserInfo={NSInvalidValue=^(?'major'\d+)\.(?'minor'\d+)(?:\.(?'patch'\d+))?(?:-(?'preRelease'(?:(?'preReleaseId'[0-9A-Za-z-]+)\.?)+))?(?:\+(?'build'(?:(?'buildId'[0-9A-Za-z-]+)\.?)+))?$}: file /BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-900.0.74.1/src/swift/stdlib/public/core/ErrorType.swift, line 181
Why? I can't find anything online about what NSRegularExpression
expects/accepts, so I don't know what I did wrong here.
Swift code:
public static let regex = try! NSRegularExpression(pattern:
"^(?'major'\\d+)\\." +
"(?'minor'\\d+)" +
"(?:\\.(?'patch'\\d+))?" +
"(?:-(?'preRelease'(?:(?'preReleaseId'[0-9A-Za-z-]+)\\.?)+))?" +
"(?:\\+(?'build'(?:(?'buildId'[0-9A-Za-z-]+)\\.?)+))?$",
options: .caseInsensitive)
It appears you are trying to use named groups in your regex. NSRegularExpression
named groups use angle brackets rather than single quotes which you have in your regex. Try using the syntax
`(?<groupName>...)`
for your named capture groups.