LoginSignup
1
2

More than 5 years have passed since last update.

python基礎 | 正規表現 初歩の初歩

Last updated at Posted at 2017-10-26

使い方すぐ忘れる。。。とても参考にしたのはこちら。

Pythonでの正規表現の使い方

使い方

>>> pattern = r"ca"
>>> s = "canada"
>>> r = re.compile(pattern)
>>> r.match(s).group()
'ca'

group()のところ、search()とかいろいろある。

自己問答

Q) rってなんだっけ。

A)

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

raw文字列にするかしないか。下でテストをしていますが、エスケープシーケンスのことを気にしないでよいので、rを付けておいたほうがよいでしょう。

Q) raw文字列にするかしないか、って何をだっけ?

A) patternと対象の文字列の2つ。
Python の raw 文字列を用いて正規表現を書くを参考に。

pattern も string も raw 文字列

>>> re.findall(r'\\\'', r'backslash \' single quote')
["\\'"]
>>> print re.findall(r'\\\'', r'backslash \' single quote')[0]

pattern も string も 普通の文字列(バックスラッシュのエスケープが必要)

>>> re.findall('\\\\\'', r'backslash \\\' single quote')
["\\'"]
>>> print re.findall('\\\\\'', r'backslash \\\' single quote')[0]
Q) あれ、raw文字列ってそもそも何か違うの。。。

A) Pythonのバックスラッシュの話を参考に、試し打ちをするとraw文字列と文字列の違いがよくわかりました。raw文字列だとr'\n'で \n とprintされる、エスケープシーケンスじゃなくなるのかぁ。

文字列

>>> s = '\\'; s; len(s) ;print(s)
'\\'
1
\
>>> s = '\n'; s; len(s) ;print(s)
'\n'
1

>>> s = '\'; s; len(s) ;print(s)
  File "<stdin>", line 1
    s = '\'; s; len(s) ;print(s)
                               ^
SyntaxError: EOL while scanning string literal
>>>
>>>

raw文字列

>>> s = r'\\'; s; len(s) ;print(s)
'\\\\'
2
\\
>>> s = r'\;'; s; len(s) ;print(s)
'\\;'
2
\;
>>> s = r'\n'; s; len(s) ;print(s)
'\\n'
2
\n
>>> s = r'\'; s; len(s) ;print(s)
  File "<stdin>", line 1
    s = r'\'; s; len(s) ;print(s)
                                ^
SyntaxError: EOL while scanning string literal
>>>

その他参考

Windowsのパスがうまく指定\表示できない問題 in Python

あとがき

勉強した時にメモを残すことを肝に命じます。でないと、繰り返し調べている。。。

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