简体   繁体   English

如何仅在 Python 正则表达式中保留捕获的组?

[英]How to keep a captured group only in Python regex?

Please accept my apology if this is a dumb question.如果这是一个愚蠢的问题,请接受我的道歉。

I want to make a regex expression that can make the two following changes in Python.我想制作一个正则表达式,可以在 Python 中进行以下两个更改。

  1. $12345.67890 to 12345.67 $12345.6789012345.67
  2. $12345 to 12345 $1234512345

What would be an appropriate regex expression to make both changes?进行这两项更改的适当正则表达式是什么?

Thank you in advance.先感谢您。

We can try using re.sub here:我们可以在这里尝试使用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)

This prints:这打印:

Here is a value 12345.67 for replacement.

Here is an explanation of the regex pattern:以下是正则表达式模式的解释:

\$                  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

in notepad++ style i would do something like find \$(\d+\.)(\d\d)\d+ Replace \1\2在记事本++风格中,我会做类似 find \$(\d+\.)(\d\d)\d+ Replace \1\2

hope that helps希望有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM