You are previewing Programming F#.

Programming F#

Cover of Programming F# by Chris Smith Published by O'Reilly Media, Inc.
O'Reilly logo

Data Processing

Once you have a fancy user interface set up for your application, the next step is doing something. There are plenty of great data-processing libraries in .NET for whatever your application needs.

Regular Expressions

Manipulating text is one of the most common tasks you will encounter. Because strings in .NET are immutable, it can be difficult to search and modify them. Fortunately .NET has the full support for regular expressions.

Regular expressions are a formal language for searching text for particular words or sequences of characters. You can use regular expressions in .NET to simplify processing textual data to do things like:

  • Validate input against a particular form

  • Identify substrings that match a particular structure

  • Create new strings that are modified versions of the input

To start with, consider the following code snippet. It defines a symbolic function =~= that takes a string and a regular expression—the format for which we will cover shortly—and returns if the string matches the given regular expression. The regular expression provided, "\d+", checks if the string contains a number:

> // Simple regular expressions
open System.Text.RegularExpressions

let (=~=) str regex = Regex.IsMatch(str, regex);;

val ( =~= ) : string -> string -> bool

> "Does this contain a number?" =~= "\d+";;
val it : bool = false
> "Does this (42) contain a number?" =~= "\d+";;
val it : bool = true

Metacharacters

Regular expressions are built on their own language of metacharacters. The ...

The best content for your career. Discover unlimited learning on demand for around $1/day.