1
0

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 の #正規表現 のあの r でパターンを囲ってるやつ‥あいつ‥なんだよ‥ふざけるなよ‥答えは? ( raw string 記法 )

Last updated at Posted at 2019-04-21

主にバックスラッシュ対策のようだ。もっと特別なことをしているのかと思っていたぜ。

Pythonでの正規表現の使い方 - Qiita

それから、パターンの最初にrを付けることをを勧めします、付けなくても基本的には大丈夫ですが、付けることによって文字列中のバックスラッシュ文字をそのままバックスラッシュとして扱えるので、パターンの書き方が分かりやすくなります。

re — Regular expression operations — Python 3.7.3 documentation

Regular expressions use the backslash character ('') to indicate special forms or to allow special characters to be used without invoking their special meaning. This collides with Python’s usage of the same character for the same purpose in string literals; for example, to match a literal backslash, one might have to write '\\' as the pattern string, because the regular expression must be \, and each backslash must be expressed as \ inside a regular Python string literal.

The solution is to use Python’s raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with 'r'. So r"\n" is a two-character string containing '' and 'n', while "\n" is a one-character string containing a newline. Usually patterns will be expressed in Python code using this raw string notation.

e.g

>>> re.search('\\\\',  "A\\B\\C")[0]
'\\'
>>> re.search(r'\\',  "A\\B\\C")[0]
'\\'

raw string とは

image

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?