LoginSignup
16
8

More than 5 years have passed since last update.

pythonの正規表現、strとunicodeで地味にハマるやつ

Posted at
    """
    日本語文字列に対して正規表現であてるときは
    日本語文字列の文字列クラス(strかunicode)と、正規表現の文字列クラスを合わせる必要がある
    例) re.match([ここがunicodeなら], [ここもunicode])
    """

    str_japanese = '3マナのクリーチャー'
    unicode_japanese = u'3マナのクリーチャー'

    match = re.search('マナ', str_japanese)
    if match:
        print "strに対して正規表現にuフラグなしであてる"

    match = re.search(u'マナ', str_japanese)
    if match:
        print "strに対して正規表現にuフラグつけてあてる"

    match = re.search('マナ', unicode_japanese)
    if match:
        print "unicodeに対して正規表現にuフラグなしであてる"

    match = re.search(u'マナ', unicode_japanese)
    if match:
        print "unicodeに対して正規表現にuフラグつけてあてる"


    # ちなみにrフラグはstr扱い

    match = re.search(r'マナ', str_japanese)
    if match:
        print "strに対して正規表現にrフラグであてる"

    match = re.search(r'マナ', unicode_japanese)
    if match:
        print "unicodeに対して正規表現にrフラグであてる"


    """
    出力 (ちゃんとマッチしたところだけprintされる)

    >>> strに対して正規表現にuフラグなしであてる
    >>> unicodeに対して正規表現にuフラグつけてあてる
    >>> strに対して正規表現にrフラグであてる
    """
16
8
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
16
8