Polars的replace_all()方法参考捕获组进行替换。

huangapple go评论67阅读模式
英文:

Polars replace_all() Refer To Capture Groups In Replacement

问题

如何在 polars 的 replace_all 方法中引用捕获组之一以用于替换字符串?例如,我想将 "5m" 替换为 "5 metres"。在 Postgres 中,我可以这样做:

select regexp_replace(text_col, '(\d+)m ', '\1 metres ')
from my_table

在 polars 中如何实现相同的功能?

英文:

How do I refer to one of the capture groups in polars replace_all method in the replacement string? For example I want to replace "5m" with "5 metres". In Postgres I can do this:

select regexp_replace(text_col, '(\d+)m ', ' metres ')
from my_table

How could I achieve the same thing in polars?

答案1

得分: 2

你可以使用美元符号 $ 来引用捕获组。

支持的语法来自 regex crate 文档:https://docs.rs/regex/latest/regex/

pl.Series(["214365"]).str.replace_all(r"(.)(.)", "$2$1")
shape: (1,)
Series: '' [str]
[
	"123456"
]

命名捕获组示例:

pl.Series(["214365"]).str.replace_all(r"(?P<left>.)(?P<right>.)", "$right$left")
shape: (1,)
Series: '' [str]
[
	"123456"
]
英文:

You can use the dollar sign $ to refer to capture groups.

The supported syntax is from the regex crate: https://docs.rs/regex/latest/regex/

pl.Series([&quot;214365&quot;]).str.replace_all(r&quot;(.)(.)&quot;, &quot;$2$1&quot;)
shape: (1,)
Series: &#39;&#39; [str]
[
	&quot;123456&quot;
]

named capture groups example:

pl.Series([&quot;214365&quot;]).str.replace_all(r&quot;(?&lt;left&gt;.)(?&lt;right&gt;.)&quot;, &quot;$right$left&quot;)
shape: (1,)
Series: &#39;&#39; [str]
[
	&quot;123456&quot;
]

huangapple
  • 本文由 发表于 2023年5月24日 18:46:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76322679.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定