需要Python正则表达式帮助(基本)
我需要一个python正则表达式,它可以帮助我消除单词中的非法字符 条件如下:需要Python正则表达式帮助(基本),python,regex,Python,Regex,我需要一个python正则表达式,它可以帮助我消除单词中的非法字符 条件如下: 第一个字符只能是a-z 单词中的所有字符只能是a-z(小写)加上撇号和连字符- 最后一个字符只能是a-z或撇号' 你可以假设这个词总是小写的 测试数据: s = "there is' -potato 'all' around- 'the 'farm-" 预期产出: >>>print(s) there is' potato all' around the farm 我的代码目前是这样的,但无法正
s = "there is' -potato 'all' around- 'the 'farm-"
预期产出:
>>>print(s)
there is' potato all' around the farm
我的代码目前是这样的,但无法正常工作:
newLine = re.findall(r'[a-z][-\'a-z]*[\'a-z]?', s)
任何帮助都将不胜感激!谢谢 只需匹配您不需要的字符,然后通过
re.sub
>>> import re
>>> s = """potato
-potato
'human'
potatoes-"""
>>> m = re.sub(r"(?m)^['-]|-$", r'', s)
>>> print(m)
potato
potato
human'
potatoes
或
>>> m = re.sub(r"(?m)^(['-])?([a-z'-]*?)-?$", r'\2', s)
>>> print(m)
potato
potato
human'
potatoes
您可以尝试:
[a-z][a-z'\-]*[a-z]|[a-z]
试试这个:
>>> b=re.findall(r'[a-z][-\'a-z]*[\'a-z]',a)
>>> for i in b: print i
...
potato
potato
human'
potatoes
假设每个单词都被一个空格隔开,你可以找到所有有效的单词,比如:
(?你试过了吗?例如?谢谢!这几乎是准确的,但我意识到在运行示例代码时没有发现一个案例。单词的开头包含撇号‘我尝试使用你的正则表达式代码,但它没有产生你编写的预期输出’。我已经用你提供的测试数据对它进行了测试。效果很好。不过,试试这个非贪婪的方法。’rsionb=re.findall(r'[a-z][-\'a-z]*[\'a-z]?',a)
切换到双引号以消除转义:b=re.findall(r'[a-z][-'a-z]*['a-z]?',a)
(?<= |^)[a-z](?:(?:[\-\'a-z]+)?[\'a-z])?(?= |$)