正则表达式 - 匹配某些模式同时排除其他模式?

Regex - Match certain patterns while excluding others?

我有文本数据要用 Python 清理(即只保留字母数字字符)。但是,我遇到的大多数文本数据都包含表情符号。我想清除文本中的非字母数字,但仍然保留表情符号

首先,我使用Python中的emoji库将文本中的每个表情符号转换为特定的字符串模式,使其易于区分。下面显示了一个已经“demojized”(库中的文字函数)的表情符号示例:

':smiley_face:' # a "demojized" emoji.

滚动浏览数据后,我发现这些表情符号(一旦“demojized”)表现出相同的模式,在正则表达式中似乎是

':[a-z_]+:' # regex for matching emojis.

好的,所以我知道表情符号的模式,我可以从我拥有的文本数据中提取每个表情符号。问题是,我想在不同时更改表情符号模式 的情况下从非字母数字 中清除文本数据。我最初尝试清理数据:

>>> text = 'Wow.. :smiley_face: this is delicious!' # A string containing emoji
>>> cleaned_text = re.sub('[^a-zA-Z0-9]+',' ',text) # regex to keep only alphanumerics
>>> print(cleaned_text)
Wow smiley face this is delicious

显然这不是我想要的输出。我想保持emoji文字完整,如下图:

'Wow :smiley_face: this is delicious' # Desired output

到目前为止,我已经研究过先行断言之类的东西,但无济于事。是否可以使用正则表达式删除非字母数字,同时从匹配中排除 ':[a-z_]+:' 模式?如果问题不清楚,我们深表歉意。

如果您只想删除 colon-word(s)-colon 上下文中除冒号和下划线以外的所有特殊字符,您可以使用

re.sub(r'(:[a-z_]+:)|[^\w\s]|_', r'', text)

regex demo详情:

  • (:[a-z_]+:) - 捕获组 1 (</code>):<code>:,一个或多个小写 ASCII 字母或 _,以及一个 :
  • | - 或
  • [^\w\s]|_ - 除了单词和空格字符或 _ 以外的任何字符(它是一个单词字符,因此需要添加它作为替代)。

the Python demo:

import re
text = 'Wow.. :smiley_face: this is delicious!' # A string containing emoji
print( re.sub(r'(:[a-z_]+:)|[^\w\s]|_', r'', text) )
# => Wow :smiley_face: this is delicious