2015-11-11 78 views
0

我有一個日誌文件,我試圖用正則表達式解析。循環遍歷字符串數組以匹配模式

創建行從日誌文件中的數組是這樣的:

let loadLog = 
    File.ReadAllLines "c:/access.log" 
     |> Seq.filter (fun l -> not (l.StartsWith("#"))) 
     |> Seq.map (fun s -> s.Split()) 
     |> Seq.map (fun l -> l.[7],1) 
     |> Seq.toArray 

我再通過這個數組需要循環。但我認爲這不會起作用,因爲線路需要是一個字符串。

是否有一種特殊的方式來處理這樣的f#中的東西?

type ActorDetails = 
    { 
     Date: DateTime 
     Name: string 
     Email: string 
    } 

for line in loadLog do 
    let line queryString = 
     match queryString with 
     | Regex @"[\?|&]system=([^&]+)" [json] -> 
      let jsonValue = JValue.Parse(Uri.UnescapeDataString(json)) 
      { 
        Date = DateTime.UtcNow (* replace with parsed date *) 
        Name = jsonValue.Value<JArray>("name").[0].Value<string>() 
        Email = jsonValue.Value<JArray>("mbox").[0].Value<string>().[7..] 
      } 
+1

你想在循環裏做什麼?就目前而言,你的'let line queryString'將會定義一個函數 - 我懷疑這不是你想要做的事情... –

+0

@TomasPetricek是的,我添加了代碼來使它更清晰。謝謝。 – SkyeBoniwell

回答

3

使用部分主動模式(|正則表達式| _ |)做

open System.Text.RegularExpressions 

let (|Regex|_|) regexPattern input = 
    let regex = new Regex(regexPattern) 
    let regexMatch = regex.Match(input) 
    if regexMatch.Success 
    then Some regexMatch.Value 
    else None 

let queryString input = function 
    | Regex @"[\?|&]system=([^&]+)" s -> s 
    | _ -> sprintf "other: %s" input