diff --git a/README.md b/README.md index e6e60da..64f71a1 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really warrant a full blog post. These are mostly things I learn by pairing with smart people at [Hashrocket](http://hashrocket.com/). -_470 TILs and counting..._ +_471 TILs and counting..._ --- @@ -93,6 +93,7 @@ _470 TILs and counting..._ - [Dynamically Generating Atoms](elixir/dynamically-generating-atoms.md) - [Execute Raw SQL In An Ecto Migration](elixir/execute-raw-sql-in-an-ecto-migration.md) - [Expose Internal Representation](elixir/expose-internal-representation.md) +- [Include Captures With String.split](elixir/include-captures-with-string-split.md) - [List Functions For A Module](elixir/list-functions-for-a-module.md) - [Pattern Matching In Anonymous Functions](elixir/pattern-matching-in-anonymous-functions.md) - [Quitting IEx](elixir/quitting-iex.md) diff --git a/elixir/include-captures-with-string-split.md b/elixir/include-captures-with-string-split.md new file mode 100644 index 0000000..9eec9a7 --- /dev/null +++ b/elixir/include-captures-with-string-split.md @@ -0,0 +1,33 @@ +# Include Captures With String.split + +The +[`String.split/3`](http://elixir-lang.org/docs/stable/elixir/String.html#split/3) +function comes with two options: `trim` and `parts`. However, when using it +with a regex pattern, you gain access to a couple extra options, including +`include_captures`. This is because when used with a regex pattern, +`String.split` just invokes `Regex.split` which comes with extra options +like `include_captures`. + +Here is `String.split` in action by itself and with the supported `trim` +option. + +```elixir +> String.split("23d", ~r/\d+/) +["", "d"] +> String.split("23d", ~r/\d+/, trim: true) +["d"] +``` + +Adding in the `include_captures` option, we get a resulting list that +includes the value captured by the splitting regex. + +``` +> String.split("23d", ~r/\d+/, trim: true, include_captures: true) +["23", "d"] +``` + +This isn't a documented feature, so it is only supported as long as +`Regex.split` supports it and as long as `String.split` continues to +delegate to `Regex.split`. + +h/t Chris Erin