0
1

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 3 years have passed since last update.

正規表現でエスケープ文字\にマッチさせる方法

Last updated at Posted at 2021-03-03

文字列中の"\"を正規表現で一致させたいとき、"\\"のようにバックスラッシュを2つ並べただけだと、上手くいきません。

"\\\\"という感じで、バックスラッシュを4つ並べると上手くいきます。

escape_match.py
import re

escape_regex = "\\\\"
path = r"C:\User\shinonomehakase"

escape_list = [escape for escape in re.findall(escape_regex, path)]

print(escape_list)
# output ['\\', '\\']

もしくは、raw文字列を使って、

escape_match.py
escape_regex = r"\\"

escape_list = [escape for escape in re.findall(escape_regex, path)]

print(escape_list)
# output ['\\', '\\']

とすることもできます。

参考

「¥マーク文字の存在チェックについて」
https://www.atmarkit.co.jp/bbs/phpBB/viewtopic.php?topic=28495&forum=7
「re --- 正規表現操作」
https://docs.python.org/ja/3/library/re.html

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?