英文:
In Swift how do you simply "make a variable" a RegexComponent?
问题
我有这样的代码...
func blah() {
if let r = someString.firstMatch(of: /([abc])(\d{2})$/) {
blah blah .. String(r.1), String(r.2)
}
}
通常,使用正则表达式,我会将正则表达式的模式保存为一个变量。
因此,类似这样的东西:
let RX: RegexComponent = /([abc])(\d{2})$/
func blah() {
if let r = someString.firstMatch(of: RX) { ..
}
我彻底失败了,搜寻了数小时也无法实现。
有人建议你需要 any RegexComponent
。
let RX: any RegexComponent = /([abc])(\d{2})$/
func blah() {
if let r = someString.firstMatch(of: RX) { ..
}
但它根本不起作用。
firstMatch#of
的参数无疑是 RegexComponent
。
我该如何设置一个 RegexComponent
类型的变量?
英文:
I have code like this ...
func blah() {
if let r = someString.firstMatch(of: /([abc])(\d{2})$/) {
blah blah .. String(r.1), String(r.2)
}
}
Normally with a regex, i'd just keep the regex-guts as a variable.
Hence, something like this:
let RX: RegexComponent = /([abc])(\d{2})$/
func blah() {
if let r = someString.firstMatch(of: RX) { ..
}
I have completely and absolutely failed to be able to do this, and have searched for hours.
some suggest you need any RegexComponent
let RX: any RegexComponent = /([abc])(\d{2})$/
func blah() {
if let r = someString.firstMatch(of: RX) { ..
}
But it simply doesn't work.
the argument of firstMatch#of
is undoubtedly a RegexComponent
.
How the heck can I make/set a variable that is a RegexComponent
??
答案1
得分: 3
This should do the trick:
let RX = /([abc])(\d{2})$
Now, since it works, you can Alt+click on the var name (RX
), and the type inference (i.e., type of the variable "deduced" by the compiler) should tell you it's a Regex<Substring>
So you can write also:
let RX: Regex<(Substring, Substring, Substring)> = /([abc])(\d{2})$
I don't have the full explanation, since I haven't played with the new Regex
, but I guess it's because RegexComponent
is a protocol
, so there is no really an init
, and there must be something with "literals": BareSlashRegexLiterals
Example:
let string = "b12"
let RX: Regex<(Substring, Substring, Substring)> = /([abc])(\d{2})$
if let match = string.firstMatch(of: RX) {
print(match.output)
// ("b12", "b", "12")
// (original, capture#1, capture#2)
}
英文:
This should do the trick:
let RX = /([abc])(\d{2})$/
Now, since it works, you can Alt+click on the var name (RX
), and the type inference (ie, type of the variable "deduced" by the compiler) should tell you it's a Regex<Substring>
So you can write also:
let RX: Regex<(Substring, Substring, Substring)> = /([abc])(\d{2})$/
I don't have the full explanation, since I haven't played with the new Regex
, but I guess it's because RegexComponent
is protocol
, so there is no really an init
, and there must be something with "literals": BareSlashRegexLiterals
Example:
let string = "b12"
let RX: Regex<(Substring, Substring, Substring)> = /([abc])(\d{2})$/
if let match = string.firstMatch(of: RX) {
print(match.output)
// ("b12", "b", "12")
// (original, capture#1, capture#2)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论