0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[正規表現Tips] Pythonで文字列内のドットをカンマに置換する(末尾2つが数字なら置換しない)

Last updated at Posted at 2019-10-11

正規表現って普段書かなくなると、すぐ忘れちゃいますよね:sweat:
めちゃめちゃTipsですが、備忘録も兼ねて投稿します。

やりたいこと

  • 掲題の通りですが、金額等の文字列の修正を想定しています。
  • 例: 金額欄に1,000.000と入力されたときに、1,000,000に修正したい。
    • ただし、1,000.000.00と入力されたときは1,000,000.00にしたい。
  • 「そんなケースに遭遇する?」と思われるかもしれませんが、例えばOCRシステム等ではあり得るかと思います。(私の場合、まさにこれ)

コード

import re

target_text = '1,000.000.00'
replace_rule = re.compile('\.(?!\d{2}$)')

text = replace_rule.sub(',', target_text)

これでいけました。
なお、このままだと例えば 1,000.01,000,0となってしまうので、ちゃんと3つ区切りのドットだけを置換したい場合は(そもそもそんなケースが有るかは不明ですが)

import re

target_text = '1.000.00.00'
replace_rule = re.compile('\.(\d{3})')

text = replace_rule.sub(r',\1', target_text)

でいけました。

以上です。この記事が世界の誰かの役に立てば幸いです:innocent:

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?