如何使用正则表达式拆分字符串

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:部分成为正则表达式?

Leo*_*bus 7

您可以使用正则表达式"\\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)

  • 这是一个很好的干净的解决方案。我喜欢如何构建范围数组,然后使用映射从原始字符串中提取子字符串。非常优雅地使用函数式编程。(已投票) (2认同)

tom*_*ahh 5

Swift 目前还没有原生的正则表达式。但Foundation规定NSRegularExpression.

\n\n
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)\n
Run 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"\n
Run Code Online (Sandbox Code Playgroud)\n