我不知道你想提取其作品,但你的例子中的以下作品的正則表達式來選擇他們所有。
(\+|-)\d+\.?\d+(\+|-)\d+\.?[\d]+(\+|-)?[^/]*
它做出來的作品,和/取決於最後作爲一個終結者,但如果它不存在將其周圍的其他方式。
(\+|-)\d+\.?\d+(\+|-)\d+\.?\d+(\+|-)?[A-Z_\d]*
不依賴於/終止符。
要提供完美的答案,座標的上下文將是必需的。
這裏是實現代碼,給出一個字符串作爲輸入:
import (
"fmt"
"regexp"
)
func main() {
toSearch := "Atlantic Ocean +00-025/\nFrance +46+002/\nParis +48.52+002.20/\nEiffel Tower +48.8577+002.295/\nMount Everest +27.5916+086.5640+8850CRSWGS_84/\nNorth Pole +90+000/\nPacific Ocean +00-160/\nSouth Pole -90+000+2800CRSWGS_84/\nUnited States +38-097/\nNew York City +40.75-074.00/\nStatue of Liberty +40.6894-074.0447/"
ISOCoord := regexp.MustCompile(`(\+|-)\d+\.?\d+(\+|-)\d+\.?\d+(\+|-)?[A-Z_\d]*`)
result := ISOCoord.FindAll([]byte(toSearch), 11)
for _, v := range result {
fmt.Printf("%s\n", v)
}
}
回報:
+00-025
+46+002
+48.52+002.20
+48.8577+002.295
+27.5916+086.5640+8850CRSWGS_84
+90+000
+00-160
-90+000+2800CRSWGS_84
+38-097
+40.75-074.00
+40.6894-074.0447
既然你想要的2個sepearate座標中新的想法,這個計算策略的工作原理:
import (
"fmt"
"regexp"
"strconv"
)
type coord struct {
lat, long float64
}
func main() {
toSearch := "Atlantic Ocean +00-025/\nFrance +46+002/\nParis +48.52+002.20/\nEiffel Tower +48.8577+002.295/\nMount Everest +27.5916+086.5640+8850CRSWGS_84/\nNorth Pole +90+000/\nPacific Ocean +00-160/\nSouth Pole -90+000+2800CRSWGS_84/\nUnited States +38-097/\nNew York City +40.75-074.00/\nStatue of Liberty +40.6894-074.0447/"
ISOCoord := regexp.MustCompile(`((\+|-)\d+\.?\d*){2}`)
result := ISOCoord.FindAllString(toSearch, -1)
INDCoord := regexp.MustCompile(`(\+|-)\d+\.?\d*`)
answer := make([]coord, 11)
for i, v := range result {
temp := INDCoord.FindAllString(v, 2)
lat, _ := strconv.ParseFloat(temp[0], 64)
lon, _ := strconv.ParseFloat(temp[1], 64)
answer[i] = coord{lat, lon}
}
fmt.Println(answer)
}
正則表達式增加了一倍,因此它更健壯一些,但只做更快它只有一次,如果有可能的話。
的代碼也應該對轉換錯誤檢查,但可以添加。
還值得注意的是,它修剪0。如果你想保持那些陳述,即。如果012.1與12.1不相同,則可以忽略轉換以浮動並使用字符串。
代碼產生作爲浮動:
[{0 -25} {46 2} {48.52 2.2} {48.8577 2.295} {27.5916 86.564} {90 0} {0 -160} {-90 0} {38 -97} {40.75 -74} {40.6894 -74.0447}]
或
[{+00 -025} {+46 +002} {+48.52 +002.20} {+48.8577 +002.295} {+27.5916 +086.5640} {+90 +000} {+00 -160} {-90 +000} {+38 -097} {+40.75 -074.00} {+40.6894 -074.0447}]
作爲字符串