How to manipulate regex replacement strings in Elixir

不打扰是莪最后的温柔 提交于 2019-12-10 17:44:16

问题


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:


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.



来源:https://stackoverflow.com/questions/21290095/how-to-manipulate-regex-replacement-strings-in-elixir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!