Python 为什么正则表达式r';[a | | | | | | | | | | | | | | | | | | 124';检测';h';和';他';分别而不是';';作为一个整体?

Python 为什么正则表达式r';[a | | | | | | | | | | | | | | | | | | 124';检测';h';和';他';分别而不是';';作为一个整体?,python,regex,nltk,Python,Regex,Nltk,我试图在给定的文本中找到“a”、“an”、“the”。表达式r'[a |(an)|(the)]+'只识别“a”,而不识别“an”和“the” nltk.re_show(r'[a|(an)|(the)]+', 'sdfkisdfjstdskfhdsklfjkhe an skfjkla') 这给了我输出 sdfkisdfjs{t}dskf{h}dsklfjk{h}{e} {a}{n} skfjkl{a} 我也试过了 nltk.re_show(r'[a|<an>|<the>

我试图在给定的文本中找到“a”、“an”、“the”。表达式r'[a |(an)|(the)]+'只识别“a”,而不识别“an”和“the”

nltk.re_show(r'[a|(an)|(the)]+', 'sdfkisdfjstdskfhdsklfjkhe an skfjkla')
这给了我输出

sdfkisdfjs{t}dskf{h}dsklfjk{h}{e} {a}{n} skfjkl{a}
我也试过了

nltk.re_show(r'[a|<an>|<the>]+', 'sdfkisdfjstdskfhdsklfjkhe an skfjkla')
我不明白为什么人们会认出“h”和“他”


在这种情况下,什么样的正则表达式可以识别给定文本中的“a”、“an”和“the”?

方括号和圆括号的含义不同。方括号用于指定“内部的任何一个字符”

另外请注意,如果要匹配“an”,则不希望捕获停止在“a”,这意味着您必须颠倒顺序

你想要什么而不是什么

[a|(an)|(the)]+
似乎是

(an|a|the)+
或者只是

(an|a|the)
或(可读性较差)


(是的,一个问题通常有许多正则表达式)

Regex
an | a


输出
['an','a','a','a','the','a','the']

虽然这是一篇老文章,但以下内容可能与寻找答案的人有关。我的解决办法是

teststring='he was trying to snatch the token from a guy standing on an escalator in the mall'
re.findall(r'( the | a | an )', teststring)
[' the ', ' a ', ' an ', ' the ']
前导空格和尾随空格提供了搜索所需的唯一序列,因此可以避免在单词“standing”中嵌入“an”。稍后可以从结果集中删除空格,以便进一步处理


谢谢

是的,没错。但它仍然没有找到“an”和“the”。我正在使用re.findall()和nltk.re_show()进行验证。@MohitMotwani Denys的
(a | an | the)
正则表达式永远不会与
an
匹配。正如我在评论中所说,使用
r'the | an?'
@WiktorStribiżew no,但正确的解决方案是在我编辑的版本中。在字符串中的同一位置匹配替代项是不好的做法<代码>一个|或
一个|一个
在这里是最好的。它不适用于“sdfkisdfjstdskfthedsklfjkhe an skfjkla”。只识别上面长长的随机第一个单词中的“an”,而不识别“the”。@Mohit Motwani已更新!使用
r'the | an?
有人能解释为什么问题中的正则表达式可以识别“h”和“he”吗?
[the]
匹配单个字符,或者
t
h
或者
e
。是的,但是我使用了(the)而不是[the]。好的,
[(the)]
匹配单个字符,或者
t
h
e
(an?|the)
import re

text = 'sdfkisdfjstdskfhdsklfjkhe an skfjkla a dsda the dsathekoo'
array = re.findall(r'the|an|a', text)

print(array)
teststring='he was trying to snatch the token from a guy standing on an escalator in the mall'
re.findall(r'( the | a | an )', teststring)
[' the ', ' a ', ' an ', ' the ']