首页 文章

F#:如何匹配子字符串?

提问于
浏览
1

我是F#的新手,但不是编程新手 . 我的大部分经验都是在C#和SQL世界中 . MSDN和我看过的其他网站还没有让我的小脑子变得那么简单,所以我想知道你是否可以给我一个正确方向的推动 .

我正在尝试编写一个简单的函数,如果字符串为null,为空,或以“//”开头,则返回true,否则返回false .

#light

let thisIsACommentOrBlank line =
    match line with
    | null -> true
    | "" -> true
    | notSureWhatToPutHere -> true
    | _ -> false

谢谢!

Update

感谢您的所有建议,最后,我能够将所有内容折叠为lambda,如下所示:

|> List.filter (fun line -> not (System.String.IsNullOrWhiteSpace(line) || line.StartsWith("//")))

再次感谢 .

4 回答

  • 4

    您可以使用 when 子句,如下所示:

    let thisIsACommentOrBlank line =
        match line with
        | null -> true
        | "" -> true
        | s when s.StartsWith "//" -> true
        | _ -> false
    

    但就此而言,这更简单:

    let thisIsACommentOrBlank line = 
        (String.IsNullOrEmpty line) || (line.StartsWith "//")
    
  • 2

    这是一种方法:

    let thisIsACommentOrBlank line =
        match line with
        | a when System.String.IsNullOrWhiteSpace(a) || a.StartsWith("//") -> true
        | _ -> false;;
    
  • 3

    您可以使用when条件(请参阅here):

    let thisIsACommentOrBlank line =
        match line with
        | null -> true
        | "" -> true
        | s when s.StartsWith "//" -> true
        | _ -> false
    

    但是你的功能可以优化:

    let thisIsACommentOrBlank = function
    | null | "" -> true
    | s -> s.StartsWith "//"
    
  • 2

    你可以省略最后一场比赛:

    let thisIsACommentOrBlank line =
        match line with
        | null -> true
        | "" -> true
        | s -> s.StartsWith "//"
    

相关问题