正则表达式在 python 中查找部分匹配的特殊字符

Regex to find partially matched special characters in python

我有一些字符串,想匹配字符串中的特殊字符(@@,$$,><,...,^),

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

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

我想关注 o/p:

@@
$$
><
....
^

你的表情好像还好,少了一些东西:

import re

string = """
aaa@@aa;aa$$aaa;aa><aaa;aa....aaa;aaa^aa
aaa@&@aa;aa$&$aaa;aa<>aaa;aa...aaa;aaaaa

"""

expression = r'@@|$$|><|\^|\.\.\.\.'
matches = re.findall(expression, string)

print(matches)

输出

['@@', '$$', '><', '....', '^']

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


您可以尝试如下操作:

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

编辑: 当您将特殊字符括在方括号中时,它就失去了意义,例如,[.] 将匹配 . 字符。

您的问题实际上只是一个打字错误,因为您忘记转义 $^ 等正则表达式元字符。但是,我会建议另一种方法,re.split:

a = 'aaa@@aa;aa$$aaa;aa><aaa;aa....aaa;aaa^aa'
parts = re.split(r'[^@$<>\^]+', a)[1:-1]
print(parts)

这里的想法是在任何字符簇上拆分字符串 other 而不是要保留的字符。上面的脚本打印:

['@@', '$$', '><', '^']