簡體   English   中英

Python:如何在字符串中的某些單詞之間找到文本?

[英]Python: How can I find text between certain words in a string?

比如有一個字符串或者txt

"""
asfas @111 dfsfds @222 dsfsdfsfsd dsfds
dsfsdfs sdfsdgsd @333 dsfsdfs dfsfsdf @444 dfsfsd
dsfssgs sdsdg @555 fsfh
"""

想要的結果:

"""
@111
@222
@333
@444
@555
"""

使用下面的代碼,我只能看到第一個結果。

import re
html="asfas @111 dfsfds @222 dsfsdfsfsd dsfds"
result = re.search('@"(.+?) ', html)
x = (result.group(0))
print(x)

如何改進我的代碼?

您可以使用re.findall方法代替re.search (re.search 僅搜索正則表達式模式產生匹配的第一個位置):

import re

txt = '''asfas @111 dfsfds @222 dsfsdfsfsd dsfds
dsfsdfs sdfsdgsd @333 dsfsdfs dfsfsdf @444 dfsfsd
dsfssgs sdsdg @555 fsfh'''

print(*re.findall(r'@\d+', txt), sep='\n')

印刷:

@111
@222
@333
@444
@555

如果你總是有 @ 后跟 3 位數字,那么:

import re

text = '''asfas @111 dfsfds @222 dsfsdfsfsd dsfds
dsfsdfs sdfsdgsd @333 dsfsdfs dfsfsdf @444 dfsfsd
dsfssgs sdsdg @555 fsfh
'''

results = re.findall(r'(@\d{3})', text)

print(results)

所以()表示保留一個模式,其中 @ 后跟只有 3 位數字。

即使不使用正則表達式,您也可以這樣做:

html="asfas @111 dfsfds @222 dsfsdfsfsd dsfds"
x = [i for i in html.split() if i.startswith('@')]

輸出

['@111', '@222']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM