正则表达式匹配一个单词和我找到的第一个parenteshis

2024-03-28 14:04:04 发布

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

我需要一个正则表达式来匹配像“estabilidade”这样的词,然后匹配任何东西,直到它到达第一个parentshis。 我已经尝试了一些正则表达式,我发现在互联网上,但我有困难,使我自己的正则表达式,因为我不明白它如何工作得很好。 有人能帮我吗?你知道吗

我已经试过的正则表达式是:

re.search(r"([^\(]+)", resultado) -> trying to get just the parenteshis.

以及

re.search(r"estabilidade((\s*|.*))\(+", resultado).group(1)

实例(需要选取括号内的所有数字,但要知道这个数字与哪个单词有关。例如,前7个与句子“Procura por estabilidade”有关:

Procura por

estabilidade

(7)

É   assertivo(a)
com  os  outros

(5)

Procura convencer

os  outros

(7)

Espontaneamente

se  aproxima

dos outros

LIDERANÇA   INFLUÊ

10

9

(6)

Demonstra

diplomacia

(5)

Tags: toresearchgetos互联网数字just
3条回答

像这样的?你知道吗

In [1]: import re

In [2]: re.findall(r'([^()]+)\((\d+)\)', 'estabilidade_smth(10) estabilidade_other(20)')
Out[2]: [('estabilidade_smth', '10'), (' estabilidade_other', '20')]

因为您没有指定要检查匹配字符串的哪一部分,所以我包含了更多的组。你知道吗

import re

s = 'hello there estabilidade this is just some text (yes it is)'
r = re.search(r"(estabilidade([.\S]+))\(", s)
print(r.group(1))  # "estabilidade this is just some text"
print(r.group(2))  # " this is just some text"

这应该做到:

estabilidade([^(]+)

它使用的是一个消极的字符类,这是关键的外卖和一个很好的工具,在你的包。[]是字符类。它是一个字符列表,如果你把^作为第一个字符,它是一个字符列表而不是。所以[^(]表示任何不是(的字符。添加+意味着左边至少有一个项目。所以,把所有这些放在一起,我们至少需要1个非(。你知道吗

在Python中是这样的:

import re

text = "hello estabilidade how are you today (at the farm)"
print (re.search("estabilidade([^(]+)", text).group(1))

输出:

 how are you today

示例:

https://regex101.com/r/2qxa0y/1/

这里是一个学习一些基本正则表达式技巧的好网站,这将有很大的帮助:https://www.regular-expressions.info/tutorial.html

相关问题 更多 >