在swift中解析ip

时间:2017-02-03 06:04:55

标签: ios arrays regex swift string

我试图解析验证目的, 喜欢

var ip = "192.168.1.2"

所以我需要在api调用中传递这个ip来响应,因为我需要从" 192.168.1传递ip。[1-255]" 直到 255 ,才能得到答复。

我的问题是如何实现这一点,需要我通过'溢出字符串。'并移动到一个数组并搜索索引为4.直到255。

还是有其他方法可以实现吗?

3 个答案:

答案 0 :(得分:0)

总体思路:

  1. 从头到尾提取所有内容'.'
  2. 运行for循环并生成1到255之间的数字。
  3. 将步骤2中生成的数字转换为字符串,并将其附加到step1的结果。
  4. 用最后一个字符串点击api并检查是否有回应。
  5. 如果您收到回复,则打破循环并使用循环外的响应对象。
  6. 您可以使用字符串方法或正则表达式执行step1。虽然字符串方法会更好,但我会给出正则表达式的例子。

    Step1 with regex:

    ^(.*?\.)\d+$
    

    所需的字符串将被捕获为第1组。

    演示:

    https://regex101.com/r/gQKs0w/1

答案 1 :(得分:0)

//如果您有固定的本地IP,例如" 192.168.1.x"

let ip = "192.168.1.10"
let ipAry = ip.components(separatedBy: ".")
let ipStr = "\(ipAry[0]).\(ipAry[1]).\(ipAry[2])"

for i in 1...255 {
    let newIP = "\(ipStr).\(i)"
    // Call the API with ip
}

//如果您从其他服务或参考获得本地IP,那么

# load data table library used for large data sets
library('data.table')

# convert factors into character
col1 <- colnames(df1)[sapply(df1, is.factor)]  # get columns that are factors for df1
col2 <- colnames(df2)[sapply(df2, is.factor)]  # get columns that are factors for df2

for(col in col1){   # df1
  set(df1, , col, as.character( df1[[col]] ) )    # for more info on set() function, read ?`:=`
}

for(col in col2){   # df2
  set(df2, , col, as.character( df2[[col]] ) )
}

# join two data frames by the selected columns in 'on' argument
setDT(df1)[df2, on = c('Instrument', 'RecordDate', 'HourMinuteSecond','MilliSecond')]   # setDT converts data frame to data table by reference
#    Instrument RecordDate HourMinuteSecond MilliSecond L1BidPrice L1BidVolume L1AskPrice L1AskVolume Midquote i.L1BidPrice i.L1BidVolume i.L1AskPrice i.L1AskVolume
# 1:        DTE   6/4/2012         16:10:27          42       6.91         520       6.92        3917     6.92            7             8            9            10
#    i.Midquote
# 1:         11

# merge function in data table is faster than the same function in base R function. You just convert data frame into data tables.
setDT(df1)
setDT(df2)
merge(df1, df2, by = c('Instrument', 'RecordDate', 'HourMinuteSecond','MilliSecond'))

答案 2 :(得分:0)

无需拆分和迭代

func isValidIp(ip : String) -> Bool {
    let allowedIpPrefix = "192.168.1."
    if ip.hasPrefix(allowedIpPrefix) {
        let suffix = String(ip.characters.dropFirst(allowedIpPrefix.characters.count))
        if let suffixValue = Int(suffix){
            //check for "0" prefix because 192.168.1.01 is invalid ip but Int("01") will return valid 1
            if (1 ... 255).contains(suffixValue) && !suffix.hasPrefix("0") {
                return true
            }
        }
    }

    return false
}