Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract the middle part of a string in FSharp?

I want to extract the middle part of a string using FSharp if it is quoted, similar like this:

let middle =
    match original with
    | "\"" + mid + "\"" -> mid
    | all -> all

But it doesn't work because of the infix operator + in pattern expression. How can I extract this?

like image 463
newwave Avatar asked Sep 20 '10 15:09

newwave


1 Answers

I don't think there is any direct support for this, but you can certainly write an active pattern. Active patterns allow you to implement your own code that will run as part of the pattern matching and you can extract & return some part of the value.

The following is a pattern that takes two parameters (prefix and postfix string) and succeeds if the given input starts/ends with the specified strings. The pattern is not complete (can fail), so we'll use the |Name|_| syntax and it will need to return option value:

let (|Middle|_|) prefix postfix (input:string) =
  // Check if the string starts with 'prefix', ends with 'postfix' and 
  // is longer than the two (meaning that it contains some middle part)
  if input.StartsWith(prefix) && input.EndsWith(postfix) && 
     input.Length >= (prefix.Length + postfix.Length) then 
    // Strip the prefix/postfix and return 'Some' to indicate success
    let len = input.Length - prefix.Length - postfix.Length
    Some(input.Substring(prefix.Length, len))
  else None // Return 'None' - string doesn't match the pattern

Now we can use Middle in pattern matching (e.g. when using match):

match "[aaa]"  with
| Middle "[" "]" mid -> mid
| all -> all
like image 196
Tomas Petricek Avatar answered Oct 02 '22 15:10

Tomas Petricek