LoginSignup
0
0

More than 1 year has passed since last update.

浮動小数点にマッチする正規表現

Last updated at Posted at 2022-01-25

修正履歴
- 間違いを修正。@StrawBerryMoonさんありがとうございます。
- Non-capturing groupについて追加。

やり方

Pythonを使った例です。
整数、浮動小数点('10e5'などのexponentを使った表現含む)にマッチ。

import re

regex = r'[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?'

text = '22 10.08 .52667 2.96996e-05 .57E+05'

m = re.findall(rf'({regex})', text)

print([t[0] for t in m])
#=> ['22', '10.08', '.52667', '2.96996e-05', '.57E+05']

正規表現を表す文字列regex内部で()を使ったグルーピングがされているので、
regex全体をさらに()で囲ってグルーピングし取り出します。

例の中の.57E+05という表記が実際に使われるのかは分かりませんが。。

Non-capturing group

Pythonにはキャプチャーせずにグルーピングする方法があるようでした。
やり方は(?:foo)のように(の後に?:を付けます。
指数部分のキャプチャーは必要なかったので、上記のコードを書き直すと以下になります。

import re

regex = r'[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?'

text = '22 10.08 .52667 2.96996e-05 .57E+05'

m = re.findall(regex, text)

print(m)
#=> ['22', '10.08', '.52667', '2.96996e-05', '.57E+05']

参考

Regular-Expressions.info

0
0
2

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