英文:
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(["214365"]).str.replace_all(r"(.)(.)", "$2$1")
shape: (1,)
Series: '' [str]
[
"123456"
]
named capture groups example:
pl.Series(["214365"]).str.replace_all(r"(?<left>.)(?<right>.)", "$right$left")
shape: (1,)
Series: '' [str]
[
"123456"
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论