Method: Polars::StringExpr#contains

Defined in:
lib/polars/string_expr.rb

#contains(pattern, literal: false, strict: true) ⇒ Expr

Check if string contains a substring that matches a regex.

Examples:

df = Polars::DataFrame.new({"a" => ["Crab", "cat and dog", "rab$bit", nil]})
df.select(
  [
    Polars.col("a"),
    Polars.col("a").str.contains("cat|bit").alias("regex"),
    Polars.col("a").str.contains("rab$", literal: true).alias("literal")
  ]
)
# =>
# shape: (4, 3)
# ┌─────────────┬───────┬─────────┐
# │ a           ┆ regex ┆ literal │
# │ ---         ┆ ---   ┆ ---     │
# │ str         ┆ bool  ┆ bool    │
# ╞═════════════╪═══════╪═════════╡
# │ Crab        ┆ false ┆ false   │
# │ cat and dog ┆ true  ┆ false   │
# │ rab$bit     ┆ true  ┆ true    │
# │ null        ┆ null  ┆ null    │
# └─────────────┴───────┴─────────┘

Parameters:

  • pattern (String)

    A valid regex pattern.

  • literal (Boolean) (defaults to: false)

    Treat pattern as a literal string.

  • strict (Boolean) (defaults to: true)

    Raise an error if the underlying pattern is not a valid regex, otherwise mask out with a null value.

Returns:



785
786
787
788
# File 'lib/polars/string_expr.rb', line 785

def contains(pattern, literal: false, strict: true)
  pattern = Utils.parse_into_expression(pattern, str_as_lit: true)
  Utils.wrap_expr(_rbexpr.str_contains(pattern, literal, strict))
end