1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 23:28:02 +00:00

Add Include Captures With String.split as an elixir til

This commit is contained in:
jbranchaud
2016-09-12 22:41:54 -05:00
parent 4501e052d0
commit a99038dbd4
2 changed files with 35 additions and 1 deletions

View File

@@ -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)

View File

@@ -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