0
0

More than 1 year has passed since last update.

先頭から文字列検索

Last updated at Posted at 2022-10-26

目的

pythonで先頭の文字列のみを検索したく調査した。
ab, →abを対象とする。
下記2つの方法を組み合わせて解決できた。

先頭・末尾から抽出

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

複数のパターンで抽出

複数のパターンのいずれかにマッチする部分を抽出したい場合は|を使う。正規表現パターンA、パターンBをA|Bのように記述する。

解決例

import re

s1 = 'abcccccabccab'
s2 = '→abccdfs→abf'
print(re.findall('^ab|^→ab', s1))
print(re.findall('^ab|^→ab', s2))

<出力>
['ab']
['→ab']

0
0
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
0