匹配所有出现的模式,但不能用双引号括起来

2024-03-29 15:15:04 发布

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

我正在努力解决下一个任务。 例如,我有这样一句话:

(1) "Je suis arrivé en Californie il y a quatre décennies 
avec absolument rien et grâce à l'accueil que cet Etat m'a offert, 
j'ai tout obtenu ", a-t-il dit dimanche dans son ultime allocution
hebdomadaire en tant que gouverneur.
(2) En revanche, je ne crois pas que l'on puisse engager durablement des soldats 
dans un conflit long et dur sans un soutien populaire fort.
(3) This is another sample with je and in double quotes "like je here" as well.

我需要一个regexp匹配的句子,如果它包含'Je'或'Je',但不被双引号包围。现在我正在使用下一个regexp:

(.*)\s((^Je|je)|(Je|je))\s(.*) 

但当模式在双引号内时,它也匹配sentance。 例如,从上面的示例中,只有(2)和(3)个句子应该匹配regexp。你知道吗


Tags: ilet句子enunqueregexpje
1条回答
网友
1楼 · 发布于 2024-03-29 15:15:04

可以使用此正则表达式搜索字符串中的模式:

s = 'This is another sample with je and in double quotes "like je here" as well.'    
re.search(r'[jJ]e(?=(?:[^"]*"[^"]*")*[^"]*$)', s)  # Match

s = 'This is another sample with and in double quotes "like je here" as well.'
re.search(r'[jJ]e(?=(?:[^"]*"[^"]*")*[^"]*$)', s)  # No match

这假设您在字符串中平衡了双引号。你知道吗

相关问题 更多 >