简体   繁体   English

如何从(AB)点迅速获得价值

[英]How to get value from point(a b) swift

I have this kind of string: " POINT(101.650577657408 3.1653186153213) ". 我有这种字符串:“ POINT(101.650577657408 3.1653186153213) ”。

Anyone know how can I get the first and second value of POINT from this String? 任何人都知道如何从此String中获得POINT的第一个和第二个值?

You can easily spit the string using componentsSeparatedByString function. 您可以使用componentsSeparatedByString函数轻松地将字符串吐出。

let myStr = "POINT(101.650577657408 3.1653186153213)"
let characterSet = NSCharacterSet(charactersInString: "( )")
var splitString = myStr.componentsSeparatedByCharactersInSet(characterSet)
print(splitString[0])
print(splitString[1])
print(splitString[2])

The above only works if you have the complete one String. 仅当您具有完整的一个String时,以上方法才有效。

Although the NSCharacterSet solution is correct but here is another solution using the most powerful regex . 尽管NSCharacterSet解决方案是正确的,但这是使用功能最强大的正则表达式的另一种解决方案。

var error: NSError?

// Initialise the regex for a float value
let regex: NSRegularExpression = NSRegularExpression(pattern: "(\\d*\\.\\d*)", options: NSRegularExpressionOptions.CaseInsensitive, error: &error)! 

// Matches array contains all the match found for float in given string
let matches: NSArray = regex.matchesInString(str as String, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, str.length))

// You can easily get all values by enumeration
for match in matches {
    println(str.substringWithRange(match.range))
}

The benefit of this solution is it will scan all the float values and will also work in case of pattern got changed. 此解决方案的好处是它将扫描所有浮点值,并且在更改模式时也可以使用。

Try this, this will work for your string 试试这个,这将适合您的字符串

    let myStr = "POINT(101.650577657408 3.1653186153213)"
    let strWithout_POINT_openingBrace = myStr.stringByReplacingOccurrencesOfString("POINT(", withString: "")//"101.650577657408 3.1653186153213)"
    let strWithout_closingBrace = strWithout_POINT_openingBrace.stringByReplacingOccurrencesOfString(")", withString: "")//"101.650577657408 3.1653186153213"
    //now you have only space between two values
    //so split string by space
    let arrStringValues = strWithout_closingBrace.componentsSeparatedByString(" ");//["101.650577657408","3.1653186153213"]

    print(arrStringValues[0]);//first value "101.650577657408"
    print(arrStringValues[1]);//second value "3.1653186153213"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM