如何操作Elixir中的正则表达式替换字符串 [英] How to manipulate regex replacement strings in Elixir

查看:154
本文介绍了如何操作Elixir中的正则表达式替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  re_sentence_frag =%r /(\w([^ \\ \\。] | \。(?! \s | $))*)(?= \。(\s | $))/ 
Regex.replace(re_sentence_frag,哦, wo,String.capitalize(\\1))

当然,那没有效果。 (它大写字符串\\1只是一次。)我真正的意思是应用 String.capitalize / 1 替换函数发现的每个匹配项。但是第三个参数不能使用函数引用,所以通过&(String.capitalize(\\1)也不起作用。 p>

这似乎是非常重要的,我很惊讶,这是不可能的,还有另一种方法可以整齐地表达这种操作?看起来底层的Erlang库不会立即支持传递一个函数引用作为第三个参数,所以这可能不是很简单的修复Elixir。



你将如何对每个匹配的字符串进行编程?

解决方案

这里是基于 split 的一个解决方案:

 哦,一个DOG。woOf。pi是3.14159。尝试版本7.a.|> 
String.split(%r / (^ | \。)(\s + | $)/)|>
Enum.map_join(& String.capitalize / 1)

我想这不比我原来的尝试更笨拙,正则表达式是考虑更简单,因为它只需要找到句子之间的位。


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?

解决方案

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.

这篇关于如何操作Elixir中的正则表达式替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆