Method: Polars::StringExpr#replace

Defined in:
lib/polars/string_expr.rb

#replace(pattern, value, literal: false, n: 1) ⇒ Expr

Replace first matching regex/literal substring with a new string value.

Examples:

df = Polars::DataFrame.new({"id" => [1, 2], "text" => ["123abc", "abc456"]})
df.with_columns(
  Polars.col("text").str.replace('abc\b', "ABC")
)
# =>
# shape: (2, 2)
# ┌─────┬────────┐
# │ id  ┆ text   │
# │ --- ┆ ---    │
# │ i64 ┆ str    │
# ╞═════╪════════╡
# │ 1   ┆ 123ABC │
# │ 2   ┆ abc456 │
# └─────┴────────┘

Parameters:

  • pattern (String)

    Regex pattern.

  • value (String)

    Replacement string.

  • literal (Boolean) (defaults to: false)

    Treat pattern as a literal string.

  • n (Integer) (defaults to: 1)

    Number of matches to replace.

Returns:



1375
1376
1377
1378
1379
# File 'lib/polars/string_expr.rb', line 1375

def replace(pattern, value, literal: false, n: 1)
  pattern = Utils.parse_into_expression(pattern, str_as_lit: true)
  value = Utils.parse_into_expression(value, str_as_lit: true)
  Utils.wrap_expr(_rbexpr.str_replace_n(pattern, value, literal, n))
end