Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 在F#中使用正则表达式过滤字符串_Regex_F#_Functional Programming - Fatal编程技术网

Regex 在F#中使用正则表达式过滤字符串

Regex 在F#中使用正则表达式过滤字符串,regex,f#,functional-programming,Regex,F#,Functional Programming,我正在尝试使用正则表达式过滤字符串列表中的所有字符串。这是我的函数,它接受一个字符串并过滤它 let filterWord wordToFilter = Regex.Replace(wordToFilter, "[^a-zA-Z0-9/!\'?.-]", ""); 因为我想将该函数应用于字符串列表中的每个元素,所以使用list.map似乎是有意义的。下面是我使用map的尝试 let filteredWords = unfilteredWords |> List.map(fun

我正在尝试使用正则表达式过滤字符串列表中的所有字符串。这是我的函数,它接受一个字符串并过滤它

let filterWord wordToFilter = 
    Regex.Replace(wordToFilter, "[^a-zA-Z0-9/!\'?.-]", "");
因为我想将该函数应用于字符串列表中的每个元素,所以使用list.map似乎是有意义的。下面是我使用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;
开放系统;
opensystem.IO;
打开System.Text.RegularExpressions;
(*测试元素是否在列表中*)
让isInList元素查找listToCheck=
List.fold(fun a b->a | | b=elementToFind)假列表检查;
(*获取字符串并将其筛选为常用文本字符*)
让FilterWordToFilter=
Regex.Replace(wordToFilter,“[^a-zA-Z0-9/!\”?.-”,“);
(*程序的主要方法*)
[]
让主argsv=
让输入=File.ReadAllText(“Alice in Wonderland.txt”)//将所有文本读入单个字符串
让unfilterdwords=input.Split(“”);
让filteredWords=unfilteredWords |>List.map(funx->filterWord(x));
0;
任何帮助都将不胜感激,谢谢

编辑:显然,将未过滤词的值更改为硬编码字符串数组可以修复此问题。问题是我不知道如何使用split。看到这个问题:


我想您应该使用Array.map或Seq.map而不是List.map

这里有一个解决方法:使用
Array.map
而不是
List.map

请注意,您可以使用F#
.Split[|'''.]
而不是
.Split('')

我的演示中示例字符串的输出是

[|""; ""; "Alice"; "In"; "Wonderland"; ""|]

另一方面,在正则表达式的末尾放置一个
+
,就在
]
之后,以便在某种程度上优化替换过程。我认为您需要发布完整的相关代码。
未过滤单词如何声明?在我的机器上工作。你的
未过滤词是什么样子的?错误消息是string[],因此必须有一个字符串数组(而不是列表)在某个地方把事情搞砸(可能是未过滤词),请看下面的列表。我希望这会有帮助。
[|""; ""; "Alice"; "In"; "Wonderland"; ""|]