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

ozxc1zmp  于 12个月前  发布在  Swift
关注(0)|答案(2)|浏览(134)

我显然做错了什么,因为这花了我这么长时间来做以下事情:(下面的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)

字符串

y53ybaqx

y53ybaqx1#

这就简单多了:

  • 开始索引是字符串中(范围的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(string.startIndex..., in: string)) {
        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)
}

xmd2e60i

xmd2e60i2#

当您尝试使用时,您的pos1pos2超出了作用域。它们都已在if块内定义,并且它们的作用域在此结束。
我建议在顶部声明它们,以便将它们纳入范围。

let aString = "piz(123)zazz"
 let pos1: Int?  // You don't need optional here but I prefer it 
 let pos2: Int? 
 .
 .
 .
 if let p1 = pos1, p2 = pos2  { // Optional Chaining
     let range = pos1..<pos2
 }

字符串

相关问题