How to include first matching pattern as a column
08:50 11 Mar 2025

I have a dataframe df.

>>> import polars as pl
>>> 
>>> 
>>> df = pl.DataFrame({"col": ["row1", "row2", "row3"]})
>>> df
shape: (3, 1)
┌──────┐
│ col  │
│ ---  │
│ str  │
╞══════╡
│ row1 │
│ row2 │
│ row3 │
└──────┘

Now I want to create a new column new. It should be the first matched pattern in the col.

For example, For the pattern 1|2 it should produce the following output.

┌──────┬───────┐
│ col  ┆ new   │
│ ---  ┆ ---   │
│ str  ┆ str   │
╞══════╪═══════╡
│ row1 ┆ 1     │
│ row2 ┆ 2     │
│ row3 ┆ null  │
└──────┴───────┘

I tried using with the expression API, but it's returning boolean values.

>>> df.with_columns(new=pl.col('col').str.contains("1|2"))
shape: (3, 2)
┌──────┬───────┐
│ col  ┆ new   │
│ ---  ┆ ---   │
│ str  ┆ bool  │
╞══════╪═══════╡
│ row1 ┆ true  │
│ row2 ┆ true  │
│ row3 ┆ false │
└──────┴───────┘
python regex dataframe python-polars