我正在尝试使用正则表达式来过滤字符串列表中的所有字符串。这是我的函数,它接受一个字符串并对其进行过滤
let filterWord wordToFilter =
Regex.Replace(wordToFilter, "[^a-zA-Z0-9/!\'?.-]", "");
由于我想将该函数应用于字符串列表中的每个元素,因此使用List.map似乎很有意义。这是我尝试使用地图的尝试
let filteredWords = unfilteredWords |> List.map(fun x -> filterWord(x));
我希望该行将我的过滤器功能应用于列表中的每个字符串(unfilteredWords是字符串列表),但我却收到语法错误,提示
"Type mismatch. Expecting a
string [] -> 'a
but given a
'b list -> 'c list
The type 'string []' does not match the type ''a list'"
而且不知道为什么。这是完整的代码
open System;
open System.IO;
open System.Text.RegularExpressions;
(*Tests if an element is in a list*)
let isInList elementToFind listToCheck =
List.fold(fun a b -> a || b = elementToFind) false listToCheck;
(*Takes a string and filters it down to common text characters*)
let filterWord wordToFilter =
Regex.Replace(wordToFilter, "[^a-zA-Z0-9/!\'?.-]", "");
(*Main method of the program*)
[<EntryPoint>]
let main argsv =
let input = File.ReadAllText("Alice in Wonderland.txt"); //Reads all the text into a single string
let unfilteredWords = input.Split(' ');
let filteredWords = unfilteredWords |> List.map(fun x -> filterWord(x));
0;
任何帮助,将不胜感激,谢谢!
编辑:显然将unfilteredWords的值更改为硬编码的字符串数组可以修复它。问题是我不知道如何使它与分裂。
解决方法:使用Array.map
代替List.map
。
请注意,您可以使用F#.Split [|' '|]
代替.Split(' ')
。
let input = "### $$$ Alice In Wonderland ,,,,";
let unfilteredWords = input.Split [|' '|]
let filteredWords = unfilteredWords |> Array.map(fun x -> filterWord(x));
printfn "%A" filteredWords;
我的演示中样本字符串的输出是
[|""; ""; "Alice"; "In"; "Wonderland"; ""|]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句