正则表达式删除除两个单词之间之外的所有连字符

lee*_*ena 0 python regex

我正在清理文本,我想删除所有连字符和特殊字符。两个单词之间的连字符除外,例如:tic-tacs, popcorn-flavoured

我编写了下面的正则表达式,但它删除了每个连字符。

text='popcorn-flavoured---'
new_text=re.sub(r'[^a-zA-Z0-9]+', '',text)
new_text 
Run Code Online (Sandbox Code Playgroud)

我希望输出是:

popcorn-flavoured

Car*_*and 5

您可以替换正则表达式的匹配项

\n\n
-(?!\\w)|(?<!\\w)-\n
Run Code Online (Sandbox Code Playgroud)\n\n

与空字符串。

\n\n

正则表达式演示 < \xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf > Python 演示

\n\n

正则表达式将匹配前后不都是单词字符的连字符。

\n\n

Python 的正则表达式引擎执行以下操作。

\n\n
-        match \'-\'\n(?!\\w)   the previous character is not a word character\n|\n(?<!\\w)  the following character is not a word character\n-        match \'-\'\n
Run Code Online (Sandbox Code Playgroud)\n\n

(?!\\w)负前瞻(?<!\\w)是一种消极的回顾

\n