How to manipulate regex replacement strings in Eli

2019-07-06 15:02发布

I found myself wanting to do this in Elixir:

re_sentence_frag = %r/(\w([^\.]|\.(?!\s|$))*)(?=\.(\s|$))/
Regex.replace(re_sentence_frag, " oh.  a DOG. woOf. ", String.capitalize("\\1"))

Of course, that has no effect. (It capitalizes the string "\\1" just once.) What I really meant is to apply String.capitalize/1 to every match found by the replace function. But the 3rd parameter can't take a function reference, so passing &(String.capitalize("\\1") also doesn't work.

This seems so fundamental that I'm surprised it's not possible. Is there another approach that would as neatly express this kind of manipulation? It looks like the underlying Erlang libraries would not immediately support passing a function reference as the 3rd parameter, so this may not be completely trivial to fix in Elixir.

How would you program manipulation of each matched string?

1条回答
Viruses.
2楼-- · 2019-07-06 15:39

Here is one solution based on split:

" oh.  a DOG. woOf. pi is 3.14159. try version 7.a." |>
String.split(%r/(^|\.)(\s+|$)/)                      |>
Enum.map_join(&String.capitalize/1)

I guess it's not much more clumsy than my original attempt. The regex is considerably simpler, as it only needs to find the bits between sentences.

查看更多
登录 后发表回答