Skip to main content
 首页 » 编程设计

python之如果没有空格,则从字符串中获取特定单词

2025年05月04日36exmyth

我有这些字符串:

552D3AE5|HellothisIsATest__**wordIWant**|someotherstuff|0 
3685248S|HellomynameIsAlex__**wordIWant2**|someotherstuff|0 
8963252A|HelloiAm25YearsOld__**wordIWant3**|someotherstuff|0 

基本上我想要的是从这个字符串中“提取”wordIWant

不幸的是,所有这些都没有空格,所以我不能使用拆分。 我尝试使用 startswith() 但只有在开始时它才有效。

所有字符串都具有相同的模板

.....|Hello........|..... 

请您参考如下方法:

如果您的数据始终采用该格式,并且假设每一行都是不同的字符串,您可以使用:

import re 
 
strings = [ 
    "552D3AE5|HellothisIsATest__wordIWant|someotherstuff|0",  
    "3685248S|HellomynameIsAlex__wordIWant2|someotherstuff|0", 
    "8963252A|HelloiAm25YearsOld__wordIWant3|someotherstuff|0" 
] 
 
for st in strings: 
    word_i_want = re.match(r'__([^|]*)', st).group(1) 
 

这会在每个字符串中搜索两个下划线,然后搜索所有内容,直到找到一个竖线。 group(0) 将是整个匹配项,包括下划线,而 group(1) 只是 wordIWant,因为我们将其包含在括号。

编辑: 如果你的字符串只是一大块,你可以改用这个:

import re 
big_string =  
"""552D3AE5|HellothisIsATest__wordIWant|someotherstuff|0 
3685248S|HellomynameIsAlex__wordIWant2|someotherstuff|0 
8963252A|HelloiAm25YearsOld__wordIWant3|someotherstuff|0""" 
 
words_i_want = re.findall(r'__([^|]*)', big_string) 

在这种情况下,words_i_want 将是您想要的单词列表。