import re
text = "abcdefgabcdefg"
pattern = "c"
# 正規表現オブジェクトを作成
regex = re.compile(pattern)
# 探索開始位置を指定
match = regex.search(text, pos=5)
if match:
print(f"マッチ位置: {match.start()}")
else:
print("マッチしませんでした")
上記のpythonのコードだと
正規表現がマッチした場合、
変数textの文字列内のどの位置にあるかの
開始位置を取得できますが、
パターンのマッチした文字列が
変数 text内での終了位置を取得するには、
どのようにすればいいのでしょうか?
↓
Python の `re` モジュールを使う場合、
マッチした文字列の **終了位置** を取得するには、
`match.end()` を使用します。
以下のようにコードを変更すれば、
マッチした文字列の **開始位置** (`start()`) と
**終了位置** (`end()`) の両方を取得できます。
### 修正コード:
```python
import re
text = "abcdefgabcdefg"
pattern = "c"
# 正規表現オブジェクトを作成
regex = re.compile(pattern)
# 探索開始位置を指定
match = regex.search(text, pos=5)
if match:
print(f"マッチ開始位置: {match.start()}")
# ここで終了位置を取得
print(f"マッチ終了位置: {match.end()}")
else:
print("マッチしませんでした")
```
### `match.end()` について
- `match.end()` は
**マッチした文字列の最後の位置の「次のインデックス」**
を返します。
- 例えば、`match.start()` が 9 の場合、
` match.end()` は `10` になります。
### 実行結果
```plaintext
マッチ開始位置: 9
マッチ終了位置: 10
```
これにより、`text` 内で
マッチした部分の **終了位置** を取得できます! 🚀
コメント
コメントを投稿