Skip to content

Instantly share code, notes, and snippets.

@carlynorama
Last active December 6, 2022 16:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save carlynorama/1fef4a0d64913f1caa2d2881f35af96c to your computer and use it in GitHub Desktop.
Use a regular expressions to get indices from one string. Then use those indices to get the content from another. #AdventOfCode2022 #Day5 https://adventofcode.com/2022/day/5
import UIKit
let stringA = " 1 2 3 4 5 6 7 8 9"
let stringB = "[F] [R] [C] [F] [L] [Q] [F] [D] [P]"
let matches = stringA.matches(of: /\b[0-9]+\b/)
for match in matches {
print(match.0, terminator: " ")
print(match.range.lowerBound) // to prove a point about String.Index
}
print()
for match in matches {
print(stringB[match.range], terminator: "")
}
print()
func getMatchRanges(from templateString:String, using regEx:String) -> [Range<String.Index>] {
guard let regex = try? Regex(regEx) else {
print("Regex init from \(regEx) failed")
return []
}
return templateString.matches(of: regex).map( {$0.range} )
}
let ranges = getMatchRanges(from: stringA, using: #"\b[0-9]+\b"#)
let results = ranges.compactMap({ stringB[$0] })
print(results)
//There is a problem if the lines is shorter
var stringC = "[M] [V] [C]"
//It's actually pretty hard to check the bounds in a normal way.
//String.Index is weird ...
//https://stackoverflow.com/questions/39676939/how-does-string-index-work-in-swift
stringA[(String.Index(utf16Offset: 3, in: stringA)...String.Index(utf16Offset: 8, in: stringA))]
//One solution is just to make the string longer
let dif = stringA.count - stringC.count
let whiteSpace = String(repeating: " ", count: dif)
let longEnough:String = stringC.appending(whiteSpace)
let resultsFromShortString = ranges.compactMap({ longEnough[$0] })
print(resultsFromShortString)
//Or instead make it fail quietly
//https://www.vadimbulavin.com/handling-out-of-bounds-exception/
extension String {
subscript(quiet range: (Range<String.Index>)) -> Substring? {
return indices.contains(range.lowerBound) && indices.contains(range.upperBound) ? self[range] : nil
}
}
let resultsWithQuietFail = ranges.compactMap({ stringC[quiet: $0] })
print(resultsWithQuietFail)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment