LoginSignup
0
1

More than 1 year has passed since last update.

正規表現を用いたPythonで動的に値を判定する方法

Last updated at Posted at 2022-12-24

前提

ABC084-B問題での実装検討を端的にまとめる

ABC084_B問題

今回やりたいこと

  • 正規表現を用いて変数の値を反映したい
  • 毎回input値が変わるので動的に正規表現をかけて判定したい(今回動的に判定するのは文字数)

実装内容

ABC_084_B.py
import re

a, b = map(int, input().split())
s = input()

# aとbの値を受け取る値毎に動的に変更して文字数を判定する
print("Yes" if re.search(fr'[0-9]{{{a}}}-[0-9]{{{b}}}', s) else "No")

  • fr"hoge"とすることでfstring関数とrow関数を併用することが可能
  • {}は2つ重ねればエスケープすることが可能
実行結果.py
# 下記結果の通り後は上記実装方法の様に、Noneなら"No", matchするなら"Yes"として完成
3 4
269-6650
<re.Match object; span=(0, 8), match='269-6650'>

1 1
---
None

1 2
7444
None

参考

https://teratail.com/questions/336593

0
1
0

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
1