MatthewMDavis
String.split on a sub-string within a pattern?
I’m trying all sorts of things with no luck, so I thought I’d ask for some help.
I want to split a string anytime there’s a “b” in “abc”, but not in " b ". I.e., when a “b” is surrounded by whitespace, I don’t want it to be a splitting character, but an element in the array returned by the split.
String.split("abcde", regex) == ["a", "cde"]
String.split("a b cde", regex) == ["a", "b", "cde"]
So I need (I think) a way to craft a regex that looks for abc, but only splits on the b part.
Marked As Solved
jwarlander
Regex Negative Lookbehind is your friend in cases like this:
iex(24)> String.split("abcde", ~r/((?<!\s)b(?!\s)|\s)/)
["a", "cde"]
iex(25)> String.split("a b cde", ~r/((?<!\s)b(?!\s)|\s)/)
["a", "b", "cde"]
iex(26)> String.split("ab cde", ~r/((?<!\s)b(?!\s)|\s)/)
["ab", "cde"]
iex(27)> String.split("a bcde", ~r/((?<!\s)b(?!\s)|\s)/)
["a", "bcde"]
The above pattern will match a b for splitting, only if it’s entirely surrounded by non-whitespace, eg. it’s not preceded by whitespace ((?<!\s)) and it’s not followed by whitespace ((?!\s)). It’ll also split on standalone whitespace ((...|\s)).
Depending on your exact needs you may want to adjust the pattern, of course.
Also Liked
JEG2
I think the pattern can be even simpler. Can you show some sample inputs and what you want to see as outputs?
swelham
I read this blog series(sorry it’s in python) last year that I think will help. It’s about building a simple interpreter and it starts off with simple maths and then onto supporting order of operation. Also requires no regex ![]()
Last Post!
tallakt
\B matches non word boundary, ie. not at the beginning of a word
iex(9)> for s <- ["abcde", "a b cde"], do: String.split(s, ~r(\Bb|\s))
[["a", "cde"], ["a", "b", "cde"]]
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex










