正则表达式查找包含特定字符的单词

时间:2014-12-04 13:54:01

标签: python regex

我想找到一次包含char '的所有单词。

例如:

'dog
dog'
do'g

我担心^.*'.*

但它不起作用。

4 个答案:

答案 0 :(得分:1)

import re
p = re.compile(r'^[^']*'[^']*$', re.IGNORECASE | re.MULTILINE)
test_str = "'dog\ndog'\ndo'g"

re.findall(p, test_str)

确实有效。见这里。

http://regex101.com/r/yR3mM3/52

您也可以尝试

^(?=[^']*'[^']*$).*$

使用预测来查找'

答案 1 :(得分:1)

你不需要正则表达式,你可以简单地说:

return your_string.count("'") == 1

或者,如果您坚持在模块中导入re

import re
return len(re.findall("'", my_string)) == 1

答案 2 :(得分:1)

您可以使用以下正则表达式执行此操作。

^(\w*'{1}\w*)$

匹配

'dog
dog'
do'g

不匹配

dog
do''g
''dog
'dog'
dog''

查看Regex demo

答案 3 :(得分:0)

像那样:

>>> import re
>>> re.findall(r"(?<![\w'])(?:\w+'\w*|'\w+)(?![\w'])", "'dog cat dog' m'a'ow do'g")

(?<![\w'])是一个负面的背后隐藏,检查之前没有单词字符或引号。 (?![\w'])是一个负向预测,用于检查之后是否有单词字符或引号。

所以这些测试确保只有一个引用。

more about lookaround