Pythonと正規表現


遊び場


the re モジュールはPythonの組み込みパッケージですので、VSコードのようなあなたの好きなエディタからも(anaconda)jupyterノートブック、Google ColabなどのPython環境でモジュールを使うことができます.例のテキストを使用しますhttps://regexr.com/ . また、テストすることができますし、そこにそれを適用する前に式で遊ぶre 関数.では、Python/ipynbファイルのスターターです.
text = "\
RegExr was created by gskinner.com, and is proudly hosted by Media Temple. \
Edit the Expression & Text to see matches. Roll over matches or the expression for details. PCRE & JavaScript flavors of RegEx are supported. Validate your expression with Tests mode. \
The side bar includes a Cheatsheet, full Reference, and Help. You can also Save & Share with the Community, and view patterns you create or favorite in My Patterns. \
Explore results with the Tools below. Replace & List output custom results. Details lists capture groups. Explain describes your expression in plain English. \
"

検索機能


The search 関数は、式が文字列と返り値と一致するかどうかを調べるために使用されますMatch object それが一致するとき.
ここではどのように単語を検索する方法の例です.com :
from re import search

match = search('([a-zA-Z]*.com)', text)

if match:
  print("matched")
else:
  print("not matched")

print("span:", match.span())
print("group:", match.group())
print("slice text with match span:", text[match.span()[0]:match.span()[1]])

Findall関数


The findall 関数は、マッチしたリストを取得するために使用する.ここにすべての単語を見つけるの例ですy 文字:
from re import findall

matched_list = findall('([a-zA-Z]*y[a-zA-Z]*)', text)

print("list of word:", matched_list)
print("words count:", len(matched_list))

分割関数


The split 関数は、指定した式またはパターンによって分割された文字列のリストを取得するために使用します.以下は、空白文字で割ったすべての単語を取得する例です.
from re import split

splitted_words = split('\s', text)

print("list of word:", splitted_words)
print("words count:", len(splitted_words))

副機能


The sub 関数は、元のテキストから式に基づいてある文字列を置換するために使用します.ここに置き換えて元のテキストを変更する例です& with and :
from re import sub

new_text = sub('&', 'and', text)

print(new_text)