swift
1extension String {
2 func components(needle: String, beforCharsLength: UInt, afterCharsLength: UInt) -> [String]? {
3 let pattern = "(.{(beforCharsLength)})(needle)(.{(afterCharsLength)})";
4 guard let regex = try? NSRegularExpression(pattern: pattern, options:[]) else {
5 return nil
6 }
7 if let match = regex.firstMatch(in: self, options: [], range: NSRange(location: 0, length: self.count)) {
8 var result: [String] = [needle, "", ""]
9
10 for i in 0..<match.numberOfRanges {
11 if let range = Range(match.range(at: i)) {
12 let inRangeStr = String(self[self.index(self.startIndex, offsetBy: range.lowerBound)..<self.index(self.startIndex, offsetBy: range.upperBound)])
13 if i < 1 || 2 < i { continue }
14 result[i] = inRangeStr
15 if i == 2 { return result }
16 }
17 }
18 }
19 return nil;
20 }
21}
22
23class ViewController: UIViewController {
24 override func viewDidLoad() {
25 super.viewDidLoad()
26 let arr = "a/TestKEYWORDtesT/b".components(needle: "KEYWORD", beforCharsLength: 4, afterCharsLength: 4);
27 print("(arr)") // Optional(["KEYWORD", "Test", "tesT"])
28 }
29}
30
31
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/09/15 13:22
2019/09/15 13:25
2019/09/15 13:46