gpt4 book ai didi

Swift 3.1 获取两个字符之间的范围?

转载 作者:可可西里 更新时间:2023-11-01 00:00:50 24 4
gpt4 key购买 nike

我显然做错了什么,因为这让我花了很长时间来做以下事情:(下面的 Playground 代码)。

注意:Swift 3.1 ~

我只是想从 piz(123)zazz 中取出 123

let aString = "piz(123)zazz"

let startBracket: Character = "("
if let idx1 = aString.characters.index(of: startBracket) {
let pos1 = aString.characters.distance(from: aString.startIndex, to: idx1)
print("Found \(startBracket) at position \(pos1)")
}
else {
print("Not found")
}

let endBracket: Character = ")"
if let idx2 = aString.characters.index(of: endBracket) {
let pos2 = aString.characters.distance(from: aString.startIndex, to: idx2)
print("Found \(startBracket) at position \(pos2)")
}
else {
print("Not found")
}

let range = pos1..<pos2 // << this is not working, I give up!!!

let result_1 = aString.substring(with: range)

最佳答案

这更容易:

  • 起始索引为字符串中(范围
  • upperBound
  • 结束索引为字符串中)范围的lowerBound

    let aString = "piz(123)zazz"

    if let openParenthesisRange = aString.range(of: "("),
    let closeParenthesisRange = aString.range(of: ")", range: openParenthesisRange.upperBound..<aString.endIndex) {

    let range = openParenthesisRange.upperBound..<closeParenthesisRange.lowerBound
    let result = aString.substring(with: range)
    print(result)
    }
    else {
    print("Not found")
    }

替代正则表达式,它的代码更多但用途更广

let string = "piz(123)zazz"

let pattern = "\\((\\d+)\\)" // searches for 0 ore more digits between parentheses

do {
let regex = try NSRegularExpression(pattern: pattern)
if let match = regex.firstMatch(in: string, range: NSRange(location: 0, length: string.utf16.count)) {
let range = match.rangeAt(1)
let start = string.index(string.startIndex, offsetBy: range.location)
let end = string.index(start, offsetBy: range.length)
print(string.substring(with: start..<end))
} else {
print("Not Found")
}
} catch {
print("Regex Error:", error)
}

关于Swift 3.1 获取两个字符之间的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43592553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com