不以开头和结尾的单词的Python正则表达式

2024-05-13 16:55:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用pythond构造正则表达式来遵循以下规则

  1. 接受只包含字母表的单词
  2. 单词可以包含-(hypen)
  3. 单词不能以特殊字符结尾,例如:)(请考虑这两个)
  4. Word不能以¨(下划线)开头,但可以以¨(下划线)结尾

例如

接受话语

Hello
Hello-World
Hello_
Hello1

拒绝文字

^{pr2}$

我想出了以下正则表达式

'(?!_)[\w-]+(?!:)'

它仍然接受所有的单词,只是在stat中跳过,最后:

有人能指出,我的正则表达式有什么问题吗 谢谢


Tags: helloworld规则结尾单词字母表statword
2条回答

在您所要求的内容中仍然有相当多的模糊性,但是这里是您给出的示例集的另一个解决方案,在此之前fiddle

^[A-Za-z-]+[_\d]?$

您可以添加前导和尾随\b。在

words = ["Hello", "Hello-World", "Hello_", "Hello1", "_hello_", "hello:",
         "hello:)" ]

import re

for word in words:
  print re.findall(r'\b(?!_)[\w-]+(?!:)\b', word)

输出:

^{pr2}$

来自http://docs.python.org/2/library/re.html

\b Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character.

相关问题 更多 >