Pythonの正規表現を使い、文字列からURLを抽出したいです。
下記のコードに辿り着いたのですが、これだと語尾の「です」も一緒に抽出してしまいます。
python
1import re 2pattern = "https?://[\w/:%#\$&\?\(\)~\.=\+\-]+" 3text = "テストhttps://teratail.com/です" 4url_list = re.findall(pattern, text) 5print(url_list) 6#出力結果 ['https://teratail.com/です'] 7#期待する出力 ['https://teratail.com/']
「です」を含めないように「https://teratail.com/」だけを抽出する良い方法はありませんでしょうか?
また、下記のような場合に独立してURLを取得する方法はありますでしょうか?
python
1import re 2pattern = "https?://[\w/:%#\$&\?\(\)~\.=\+\-]+" 3text = "テストhttps://teratail.com/https://teratail.com/です" 4url_list = re.findall(pattern, text) 5print(url_list) 6#出力結果 ['https://teratail.com/https://teratail.com/です'] 7#期待する出力 ['https://teratail.com/', 'https://teratail.com/']

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2022/08/13 10:22
2022/08/13 10:26
退会済みユーザー
2022/08/13 11:15