Pandas extract substring with optional in pattern

Viewed 184

From a df column 'Desc' I want to extract substrings that start with n or N followed by a digit, here's a test df with my code and result:

import pandas as pd
testdf = pd.DataFrame({'Desc': ['n1.2A Full Version', 'N5.0.0 Bridge', 'N5.35A Automatic', 'n2 Bridge']})
testdf['Version'] = testdf['Desc'].str.extract(r'([nN]\d.+?[\s])', expand=False)

How to fix the regex so that it doesn't show NaN for the last record? Thanks

1 Answers

The main issue is that .+? requires at least 1 char other than line break char and then [\s] requires a whitespace to match. So, when [nN]\d matched and consumed n2, the regex engine tries to match the next space with .+? and then [\s] fails to match a whitespace.

You may use

>>> testdf['Desc'].str.extract(r'([nN]\d\S*)', expand=False)
0     n1.2A
1    N5.0.0
2    N5.35A
3        n2

The pattern is [nN]\d\S*:

  • [nN] - n or N
  • \d - a digit
  • \S* - 0 or more non-whitespace chars

See online regex demo and the regex graph:

enter image description here

Related