Search code examples
pythonregexstringmatchpartial

Regex to find partially matched special characters in python


I have some strings, and want to match the special characters(@@,$$,><,...,^) from the string,

a='aaa@@aa;aa$$aaa;aa><aaa;aa....aaa;aaa^aa'

match=re.findall('@@|$$|><|....|^', a)
print(match)

I want following o/p:

@@
$$
><
....
^

Solution

  • You can try something like below:

    >>> a='aaa@@aa;aa$$aaa;aa><aaa;aa....aaa;aaa^aa'
    >>> match=re.findall('@{2}|[$]{2}|><|[.]{4}|\^', a)
    >>> match
    ['@@', '$$', '><', '....', '^']
    

    Edit: When you enclose a special character inside brackets it loses its meaning, e.g., [.] will match the . character.