xxm*_*exx 6 regex string split swift swift3
我有一个字符串"323 ECO Economics Course 451 ENG English Course 789 Mathematical Topography"我想使用regex表达式拆分此字符串,[0-9][0-9][0-9][A-Z][A-Z][A-Z]以便该函数返回数组:
Array =
["323 ECO Economics Course ", "451 ENG English Course", "789 Mathematical Topography"]
Run Code Online (Sandbox Code Playgroud)
我将如何使用swift进行此操作?
编辑
我的问题与链接的问题不同.我意识到你可以在swift中拆分一个字符串myString.components(separatedBy: "splitting string").问题是该问题没有解决如何制作splitting string一个正则表达式.我尝试使用mystring.components(separatedBy: "[0-9][0-9][0-9][A-Z][A-Z][A-Z]", options: .regularExpression)但是没有用.
如何使该separatedBy:部分成为正则表达式?
您可以使用正则表达式"\\b[0-9]{1,}[a-zA-Z ]{1,}"和此答案的扩展名,通过文字,caseInsensitive或regularExpression搜索来获取字符串的所有范围:
extension StringProtocol {
func ranges(of string: Self, options: String.CompareOptions = []) -> [Range<Index>] {
var result: [Range<Index>] = []
var startIndex = self.startIndex
while startIndex < endIndex,
let range = self[startIndex...].range(of: string, options: options) {
result.append(range)
startIndex = range.lowerBound < range.upperBound ? range.upperBound :
index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
}
return result
}
}
Run Code Online (Sandbox Code Playgroud)
let inputString = "323 ECO Economics Course 451 ENG English Course 789 Mathematical Topography"
let courses = inputString.ranges(of: "\\b[0-9]{1,}[a-zA-Z ]{1,}", options: .regularExpression).map{inputString[$0] }
print(courses) // ["323 ECO Economics Course ", "451 ENG English Course ", "789 Mathematical Topography"]
Run Code Online (Sandbox Code Playgroud)
Swift 目前还没有原生的正则表达式。但Foundation规定NSRegularExpression.
import Foundation\n\nlet toSearch = "323 ECO Economics Course 451 ENG English Course 789 MAT Mathematical Topography"\n\nlet pattern = "[0-9]{3} [A-Z]{3}"\nlet regex = try! NSRegularExpression(pattern: pattern, options: [])\n\n// NSRegularExpression works with objective-c NSString, which are utf16 encoded\nlet matches = regex.matches(in: toSearch, range: NSMakeRange(0, toSearch.utf16.count))\n\n// the combination of zip, dropFirst and map to optional here is a trick\n// to be able to map on [(result1, result2), (result2, result3), (result3, nil)]\nlet results = zip(matches, matches.dropFirst().map { Optional.some($0) } + [nil]).map { current, next -> String in\n let range = current.rangeAt(0)\n let start = String.UTF16Index(range.location)\n // if there\'s a next, use it\'s starting location as the ending of our match\n // otherwise, go to the end of the searched string\n let end = next.map { $0.rangeAt(0) }.map { String.UTF16Index($0.location) } ?? String.UTF16Index(toSearch.utf16.count)\n\n return String(toSearch.utf16[start..<end])!\n}\n\ndump(results)\nRun Code Online (Sandbox Code Playgroud)\n\n运行此命令将输出
\n\n\xe2\x96\xbf 3 elements\n - "323 ECO Economics Course "\n - "451 ENG English Course "\n - "789 MAT Mathematical Topography"\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
6563 次 |
| 最近记录: |