gpt4 book ai didi

python-3.x - 正则表达式匹配单词结尾或以连字符开头

转载 作者:行者123 更新时间:2023-12-04 12:30:15 25 4
gpt4 key购买 nike

我正在尝试创建一个正则表达式来删除任何以连字符开头或结尾的单词(不是两者)。

word1- -> 删除-word2 -> 删除分词 ->保留

我的尝试如下:

def begin_end_hyphen_removal(line):
return re.sub(r"((\s+|^)(-[A-Za-z]+)(\s+|$))|((\s+|^)([A-Za-z]+-)(\s+|$))","",line)

但是,当我尝试将它应用于以下行时:

here are some word sub-words -word1 word2- sub-word2 word3- -word4
-word5 example
word6-
word7-
another one -word8
-word9

我再次得到与输出相同的输入。

最佳答案

你可以使用

r'\b(?<!-)[A-Za-z0-9]+-\B|\B-[A-Za-z0-9]+\b(?!-)'
r'\b(?<!-)\w+-\B|\B-\w+\b(?!-)'

参见 regex demo . 详细信息:

  • \b(?<!-)\w+-\B - 一个或多个不以 - 开头的字符然后是 -位于字符串末尾或非单词字符之前的字符
  • | - 或者
  • \B-\w+\b(?!-) - 一个 -它要么在字符串的开头,要么在一个非单词字符之后,然后是一个或多个没有跟随 - 的单词字符.

参见 Python demo :

import re
rx = re.compile( r' *(?:\b(?<!-)\w+-\B|\B-\w+\b(?!-))' )
text = 'here are -some- word sub-words -word1 word2- sub-word2 word3- -word4\n-word5 example\nword6-\nword7-\nanother one -word8\n-word9'
print( rx.sub('', text) )

输出:

here are -some- word sub-words sub-word2
example


another one

关于python-3.x - 正则表达式匹配单词结尾或以连字符开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69615920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com