为什么我的SemVer正则表达式不能运行?

时间:2022-11-26 10:15:24

I'm trying to make a regex that matches a semantic version (SemVer) 2.0.0. This is my first try:

我正在尝试创建一个与语义版本(SemVer) 2.0.0匹配的regex。这是我的第一次尝试:

^(?'major'\d+)\.(?'minor'\d+)(?:\.(?'patch'\d+))?(?:-(?'preRelease'(?:(?'preReleaseId'[0-9A-Za-z-]+)\.?)+))?(?:\+(?'build'(?:(?'buildId'[0-9A-Za-z-]+)\.?)+))?$

RegEx101

RegEx101

This passes my smoke tests, but when I try to actually make it a NSRegularExpression, I get this:

这通过了烟雾测试,但是当我尝试将它变成NSRegularExpression,我得到了:

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.

为什么?我在网上找不到NSRegularExpression期望/接受什么,所以我不知道我在这里做错了什么。


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)

1 个解决方案

#1


1  

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

似乎您正在尝试在regex中使用命名组。命名为groups的NSRegularExpression使用尖括号,而不是regex中的单引号。尝试使用语法

`(?<groupName>...)`

for your named capture groups.

为您命名的捕获组。

#1


1  

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

似乎您正在尝试在regex中使用命名组。命名为groups的NSRegularExpression使用尖括号,而不是regex中的单引号。尝试使用语法

`(?<groupName>...)`

for your named capture groups.

为您命名的捕获组。