4
2

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 1 year has passed since last update.

Pythonを使って特定パターンの文字列が含まれるかを正規表現で判定する

Last updated at Posted at 2023-09-10

正規表現で判定するために、re.findall()を使用する。

re.findall()はマッチするすべての部分を文字列のリストとして返す。
第一引数に正規表現パターンの文字列、第二引数に対象の文字列を指定する。
 import re
 re.findall(r'\d+', s)

\dは数字、+は直前のパターンを1回以上繰り返すことを表している。
\d+は連続した1文字以上の数字にマッチする。
rを付けてエスケープシーケンスを無効化するraw文字列を使う。

.は改行以外の任意の1文字、*は直前のパターンの0回以上の繰り返し。
例えば、a.*bはaで始まってbで終わる文字列にマッチする。

+は直前のパターンの1回以上の繰り返し。
a.+bの場合、abにはマッチしない。

?は直前のパターンが0回か1回。
a.?bの場合、abおよびaとbの間に1文字だけが存在している場合にのみマッチ

*, +, ?は貪欲(greedy)マッチで、できるだけ長いテキストを返す。
*?, +?, ??とすると、非貪欲(non-greedy)、最小(minimal)マッチとなり、できるだけ短いテキストを返す。

[]で文字列を囲むと、その中の文字のいずれか1文字にマッチする。*, +, ?などと組み合わせることも可能。

先頭から始まる文字列のみを抽出したい場合はメタ文字^(先頭にマッチ)、または、末尾で終わる文字列のみを抽出したい場合は $(末尾にマッチ)を使う。

複数のパターンのいずれかにマッチする部分を抽出したい場合は|を使う。

デフォルトでは大文字と小文字を区別して処理される。
引数flagsにre.IGNORECASEを指定すると、大文字と小文字が区別されなくなる。

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?