简体   繁体   中英

python - unicode regex match - how do I search for the checkmark? ✓

I am trying to match against lines that contain a checkmark in them: ✓

I'm using python3.

The unicode encoding can be read about here: https://codepoints.net/U+2713?lang=en

The line I'm trying to match against looks like this:

✓ Chrome on MAC - MySite.com - version-1

re.match("✓", line) does not work. re.match("/u2713", line) does not work either.

How can I determine if the line contains a ✓?

--- UPDATE ---

solved : apparently there was an invisible character of some sort preceding the ✓ and this caused the match operator to fail. Thanks to @NickT and @EricDuminil for clueing me in. Also, the in operator appears to be easier and safer, so I'm marking that answer as correct.

You don't even need any regex. You could use the in operator :

>>> "✓" in "✓ Chrome on MAC - MySite.com - version-1"
True
>>> "✓" in "Chrome on MAC - MySite.com - version-1"
False

If you want to display the lines with a checkmark inside 'marks.txt' , you can write:

with open('marks.txt') as f:
    for line in f:
        if "✓" in line:
            print(line, end='')

For a fool-proof method, specify the character by name:

>>> line = '✓ Chrome on MAC - MySite.com - version-1'
>>> re.match('\N{CHECK MARK}', line)
<_sre.SRE_Match object; span=(0, 1), match='✓'>

How can I determine if the line contains a ✓?

Example:

import re


text = '''
123 456 789
✓ 123 456 789
123 456 789
123 456 ✓ 789
123 456 789
'''

for m in re.finditer('^.*✓.*$', text, re.MULTILINE):
    print('line:', m.group(0))

Prints:

line: ✓ 123 456 789
line: 123 456 ✓ 789

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM