正则表达式,英语到 Pig Latin - 如何修复大写

Regex, English to Pig Latin - how to fix capitalization

编辑:原问题偏离主题,编辑更正。

我在学习 Elixir 时遇到了一些编码挑战,遇到了一个将英语翻译成 Pig Latin on Wikipedia 的挑战。

我开始为不同的规则制定正则表达式,并意识到一次完成所有这些并不难。在玩了一会儿之后,我得出了以下结果来一次匹配和转换一个单词。

Elixir 应该使用 PCRE 兼容的正则表达式,但我一直没能找到一种方法让 \u one character to upper and \L All characters to lower 在 elixir 字符串替换中工作。我已经尝试了几种将它们用于替换字符串的变体,但完全找不到可行的方法。

有没有办法在 elixir 中使用纯 Regex String.replace 我需要用常规代码处理其余部分吗?

iex(21)> regex = ~r/(^(?:[aeiouAEIOU]|[XYxy][^aeiouy])(?:.*))|(?:^([A-Z][^aeiou]*(?:u)?)([aeiouy].*))|(?:^([^aeiou]*(?:u)?)([aeiouy].*))/
~r/(^(?:[aeiouAEIOU]|[XYxy][^aeiouy])(?:.*))|(?:^([A-Z][^aeiou]*(?:u)?)([aeiouy].*))|(?:^([^aeiou]*(?:u)?)([aeiouy].*))/
iex(22)> String.replace("Squirl", regex, "\1\u\3\L2\5\4ay")
"\uirl\L2ay"
iex(23)> String.replace("Squirl", regex, "\1\3\2\5\4ay")
"irlSquay"

原题如下:

请注意我完全说的挑战,以元音开头的单词只需将 'ay' 附加到末尾即可。其他一些说明说 "way" 或 "yay"

Powershell 版本:

[Regex]$reg = '(^(?:[aeiou]|[xy][^aeiouy])(?:.*))|(?:^([^aeiou]*(?:u)?)([aeiouy].*))'
'powershell' -replace $reg, ('' + 'ay')

长生不老药版本:

regex = ~r/(^(?:[aeiou]|[xy][^aeiouy])(?:.*))|(?:^([^aeiou]*(?:u)?)([aeiouy].*))/i
String.replace("elixir", regex, "\1\3\2ay")

这看起来很简单,有没有我遗漏的案例?

来自 elixir regex documentation, you can see it is based on erlang's :re 其中明确指出:

The matching algorithms of the library are based on the PCRE library, but not all of the PCRE library is interfaced

然后:

Unsupported Escape Sequences

In Perl, the sequences \l, \L, \u, and \U are recognized by its string handler and used to modify the case of following characters. PCRE does not support these escape sequences.


解决方法

您必须将 String.replace 与“接收匹配模式的函数并且必须 return 替换为字符串或 iodata”作为 replacement(第三个)参数一起使用。