首页 > 解决方案 > 如何仅在 Python 正则表达式中保留捕获的组?

问题描述

如果这是一个愚蠢的问题,请接受我的道歉。

我想制作一个可以在 Python 中进行以下两个更改的正则表达式。

  1. $12345.6789012345.67
  2. $1234512345

进行这两项更改的适当正则表达式是什么?

先感谢您。

标签: pythonregex

解决方案


我们可以re.sub在这里尝试使用:

inp = "Here is a value $12345.67890 for replacement."
out = re.sub(r'\$(\d+(?:\.\d{1,2})?)\d*\b', '\\1', inp)
print(out)

这打印:

Here is a value 12345.67 for replacement.

以下是正则表达式模式的解释:

\$                  match $
(                   capture what follows
    \d+             match one or more whole number digits
    (?:\.\d{1,2})?  then match an optional decimal component, with up to 2 digits
)                   close capture group (the output number you want)
\d*                 consume any remaining decimal digits, to remove them
\b                  until hitting a word boundary

推荐阅读