迅速分裂" abc1.23.456.7890xyz"进入" abc"," 1"," 23"," 456"," 7890"和" xyz"

时间:2015-11-16 18:26:06

标签: regex macos swift2 nsregularexpression

在OS X上的Swift中我试图删除字符串" abc1.23.456.7890xyz"进入这些字符串:

"abc"
"1"
"23"
"456"
"7890"
"xyz"

但是当我运行以下代码时,我得到以下内容:

=> "abc1.23.456.7890xyz"
(0,3) -> "abc"
(3,1) -> "1"
(12,4) -> "7890"
(16,3) -> "xyz"

这意味着应用程序正确找到" abc",第一个令牌" 1",但随后找到的下一个令牌是" 7890" (错过" 23"和" 456")然后是" xyz"。

任何人都可以看到如何更改代码以查找所有字符串(包括" 23"和" 456")?

非常感谢提前。

import Foundation
import XCTest

public
class StackOverflowTest: XCTestCase {
    public
    func testRegex() {
        do {
            let patternString = "([^0-9]*)([0-9]+)(?:\\.([0-9]+))*([^0-9]*)"
            let regex = try NSRegularExpression(pattern: patternString, options: [])

            let string = "abc1.23.456.7890xyz"
            print("=> \"\(string)\"")

            let range = NSMakeRange(0, string.characters.count)
            regex.enumerateMatchesInString(string, options: [], range: range) {
                (textCheckingResult, _, _) in
                if let textCheckingResult = textCheckingResult {
                    for nsRangeIndex in 1 ..< textCheckingResult.numberOfRanges {
                        let nsRange = textCheckingResult.rangeAtIndex(nsRangeIndex)
                        let location = nsRange.location
                        if location < Int.max {
                            let startIndex = string.startIndex.advancedBy(location)
                            let endIndex = startIndex.advancedBy(nsRange.length)
                            let value = string[startIndex ..< endIndex]
                            print("\(nsRange) -> \"\(value)\"")
                        }
                    }
                }
            }
        } catch {
        }
    }
}

2 个答案:

答案 0 :(得分:2)

这都是关于你的正则表达式模式。您想要找到一系列连续的字母或数字。请尝试使用此模式:

let patternString = "([a-zA-Z]+|\\d+)"

答案 1 :(得分:0)

替代&#39; Swifty&#39;方式

let str = "abc1.23.456.7890xyz"
let chars = str.characters.map{ $0 }

enum CharType {
    case Number
    case Alpha
    init(c: Character) {
        self = .Alpha
        if isNumber(c) {
            self = .Number
        }
    }
    func isNumber(c: Character)->Bool {
        return "1234567890".characters.map{ $0 }.contains(c)
    }    
}

var tmp = ""
tmp.append(chars[0])
var type = CharType(c: chars[0])

for i in 1..<chars.count {
    let c = CharType(c: chars[i])

    if c != type {
        tmp.append(Character("."))
    }
    tmp.append(chars[i])
    type = c
}
tmp.characters.split(".", maxSplit: Int.max, allowEmptySlices: false).map(String.init)
// ["abc", "1", "23", "456", "7890", "xyz"]