获取具有特定前缀和后缀的字符串的`Middle`?

时间:2014-11-11 18:19:10

标签: f#

以下活动模式不使用正则表达式以获得更好的性能。但是,这似乎是程序性的风格。这是用F#写的更好的方法吗?

let (|Middle|_|) prefix postfix (input : string) =
    if input.StartsWith(prefix) && input.EndsWith(postfix)
          && input.Length > prefix.Length + postfix.Length then
        let len = input.Length - prefix.Length - postfix.Length
        Some(input.Substring(prefix.Length, len))
    else None

1 个答案:

答案 0 :(得分:2)

我认为没关系。 为什么你认为它不起作用? 我只会改变最后一行才能使用字符串切片:

if input.StartsWith(prefix) && input.EndsWith(postfix)
      && input.Length > prefix.Length + postfix.Length then
    Some(input.[prefix.Length .. input.Length - postfix.Length - 1])
else None

无论如何,我认为它不会使它更具功能性。