1

次のコード例では、正規表現で文字列のリストをフィルタリングしています。その文字列に一致するエントリは 1 つしかないことがわかっています。次に、同じ一致文字列を使用して、残りの 1 つの値からグループ化された 2 つの値を取得します。

let input = ["aaaa bbbb";"aaabbbb";"cccc$$$$";"dddddda";" "] 

let ValuesOfAB (input: string list) = 
    let matchString = "(?<a>\w+)\s(?<b>\w+)"

    let value = input |> List.filter (fun line -> Regex.Matches(line, matchString).Count <> 0) 
                      |> List.head
    (Regex.Matches(value, matchString).[0].Groups.["a"].Value, Regex.Matches(value, matchString).[0].Groups.["b"].Value)

let a = ValuesOfAB input

戻りたい値を取得するために、同じ文字列で Regex.Matches をもう一度使用する必要がないより良い方法はありますか?

4

1 に答える 1

3

List.pickを使用します。

let input = ["aaaa bbbb";"aaabbbb";"cccc$$$$";"dddddda";" "] 

let valuesOfAB (input: string list) = 
    let matchString = "(?<a>\w+)\s(?<b>\w+)"
    let v = input |> List.pick (fun line -> let m = Regex.Match(line, matchString)
                                            if m.Success then Some m else None)
    v.Groups.["a"].Value, v.Groups.["b"].Value

let a = valuesOfAB input

説明:

Regex を再度実行する必要がないように、リストの最初の文字列を照合してMatchオブジェクトを返したいとします。List.pickタスクに非常によく適合します。

各文字列で、少なくとも 1 回一致する必要があり、目的には十分ですRegex.MatchMatch.Success

于 2012-07-04T21:35:40.877 に答える