LoginSignup
3
2

More than 5 years have passed since last update.

[python]何かに囲まれた間のテキストを取得したい

Last updated at Posted at 2018-09-13

見つからなかったので作成して公開。

Thanks!!

2018/09/15 @uasiさんから編集リクエストをいただき、マージしました!ありがとう!!!

extract_text.py
- match_obj = re.search(begin + '(.*)' + end), text)
+ match_obj = re.search(re.escape(begin) + '(.*)' + re.escape(end), text)

コード

extract_text.py
def extract_text(begin, end, text):
    match_obj = re.search(re.escape(begin) + '(.*)' + re.escape(end), text)
    pretty_text = match_obj.groups()[0]
    return pretty_text

注意点

re.searchで取得してるので、最初にマッチしたもののみ取得します。

メモ

htmlタグのタグ内のテキストコンテンツを取得する時とかに使えると思います(そういう用途で作った)。

※今の使い方なら大丈夫だけど、.*というマッチではダメな場合も出てくるかも???
-> https://blog.mah-lab.com/2014/06/07/regular-expression-lazy-quantifiers/

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