我是编程新手,F#是我的第一个.NET语言。F#:Try-with block用于检查正则表达式模式是否有效
作为一个初学者的项目,我想创建一个正则表达式查询工具,它将确定用户输入的正则表达式模式是否有效。我被告知,我可以通过try-with块来查看是否编译正则表达式模式,但由于我对编程通常还是非常陌生,所以我无法使用this method,因为我不知道指定什么第二个参数。
- 我在寻找正确的方法吗?
- 一个更有经验的程序员能告诉我如何编写一个能完成刚才描述的任务的函数吗?
谢谢。
编辑:这里是我的代码至今:
open System
open System.IO
open System.Text.RegularExpressions
let askUserForFilePath() =
Console.WriteLine("Please enter the file (extension: .txt) from which to read all lines: ")
let filePath = Console.ReadLine()
filePath
let askUserForRegexPattern() =
Console.WriteLine("Please enter a regular expression: ")
let regExp = Console.ReadLine()
regExp
let getLinesFromFile (filePath: string) =
let linesFromFile = File.ReadAllLines filePath
linesFromFile
|> Array.reduce (+)
|> string
let matchTextAgainstRegex (text: string) (regExp: string) =
try
Regex.IsMatch(text, regExp)
with
if Regex.IsMatch(text, regExp) then
let matchResults = Regex.Match(text, regExp)
let stringsFound = []
for eachGroup in matchResults.Groups do
eachGroup.Value :: stringsFound |> ignore
stringsFound
|> List.rev
|> List.iter (fun eachString -> printfn "%s" eachString)
else
我的问题是不知道如何完成试穿用块。 'else'块目前尚未完成,但我会稍后再讨论。感谢您的帮助。
你到目前为止尝试过什么?为什么它不起作用?你能否提供一个[简短,独立,正确,可编辑的例子](http://sscce.org)? – 2015-03-19 09:22:54
@MarkSeemann,我现在用一个例子来编辑我的帖子。 – 2015-03-19 09:24:58
您是否阅读过最后一个问题的完整答案(自编辑以来)?它似乎解决您的问题 – 2015-03-19 09:28:00