如何删除字符串中的某些字符?

时间:2018-05-17 09:44:55

标签: swift

字符串值有时会变化

93.93% - 94.13,85.34,%74.90,88.21%

我只需要像这样提取双值。

93.93,85.34,74.90,88.21

4 个答案:

答案 0 :(得分:0)

你应该尝试使用像这样的正则表达式:

[0-9]{2}.[0-9]{2}

这个正则表达式找到所有匹配两个数字的字符串,然后再找一个点和两个数字。

答案 1 :(得分:0)

您可以使用正则表达式从字符串中提取数字,如下所示:

let sourceString = "93.93% - 94.13, 85.34, %74.90, 88.21%"

func getNumbers(from string : String) -> [String] {
    let pattern = "((\\+|-)?([0-9]+)(\\.[0-9]+)?)|((\\+|-)?\\.?[0-9]+)" // Change this according to your requirement
    let regex = try! NSRegularExpression(pattern: pattern)
    let matches = regex.matches(in: string, range: NSRange(string.startIndex..., in: string))

    let result = matches.map { (match) -> String in
        let range = Range(match.range, in: string)!
        return String(string[range])
    }

    return result
}

let numberArray = getNumbers(from: sourceString)
print(numberArray)

结果:

["93.93", "94.13", "85.34", "74.90", "88.21"]

答案 2 :(得分:0)

对于每个值,例如var str='%74.90';,请使用此行 -

var double=str.match(/[+-]?\d+(\.\d+)?/g).map(function(v) { return parseFloat(v); })[0];

答案 3 :(得分:0)

使用Scanner扫描值。 Scanner具有高度可配置性,专为从松散划分的字符串扫描字符串和数值而设计。以下是示例:

let characterSet = CharacterSet.init(charactersIn: "0123456789.").inverted
let scanner = Scanner(string: "93.93% - 94.13, 85.34, %74.90, 88.21%")
scanner.charactersToBeSkipped = characterSet
var numStr: NSString?
while scanner.scanUpToCharacters(from: characterSet, into: &numStr) {
    print(numStr ?? "")
}

<强>输出:

93.93
94.13
85.34
74.90
88.21

比较正则表达式更容易理解。