非キャプチャグループ
from 20241104
non-capturing-group
拡張正規表現
What is a non-capturing group in regular expressions?
https://stackoverflow.com/questions/3512471
普通のカッコで囲むと、文字列のグループ化だけでなくキャプチャも行なってしまう。
本来必要のない場面で文字列のキャプチャを行うと、パフォーマンス面でも良くない場合がある。
非キャプチャグループを利用すると、文字列のグループ化のみを行うことができる。
(?:...)
利用例
code:python
import re
pattern = r'^(.*?)(?::(\d+(?:\.\d+)?))?$'
# サンプルの文字列
test_strings = "Hello:world:1.5", "Hello:world"
for string in test_strings:
match = re.match(pattern, string)
if match:
word_part = match.group(1)
number_part = match.group(2) or None
print((word_part, number_part))