Regex : Match Character if follow by string ccontainning himself

Viewed 31

I try to match the first character '.' in '-2.232.232'. I am close to it by this regex

^[^\.]*(\.)(?=.*\.)

but it match '-2.' insted of '.'.

Thank you very much

1 Answers

You can use Series.str.replace with the n argument set to 1:

import pandas as pd
df = pd.DataFrame({'Data':['-2.232.232']})
df['Data'].str.replace(r"\.(?=[^.]*\.)", "", n=1)
# => 0    -2232.232

Here,

  • \.(?=[^.]*\.) - matches a dot that is followed with any zero or more chars other than a dot and then a dot char
  • n=1 - sets the number of replacements. n=1 means only one replacement.

Alternatively, you may use

>>> df['Data'].str.replace(r"^([^.]*)\.(?=[^.]*\.)", r"\1", n=1)
0    -2232.232

Here, ^([^.]*) matches and captures into Group 1 any zero or more chars other than . from the start of the string, and the \1 refers to that value from the replacement pattern.

Related