从字符串python re库中提取子字符串

2024-10-02 14:16:13 发布

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

我有一根绳子

string = 'Ph no. : 999999999 | year: 2021 | class no.: 10Type: 2-A | S-no. : dfwef | Name : dfwf'

我想使用正则表达式python来提取类型。在这种情况下,我想要的输出是2-A

我已经试过了

import re
type = re.findall(r'Type: \d*-', string)
print(type)

我有多个这种类型的字符串,我想提取“type:”和“|”之间的代码文本


Tags: nonameimportre类型stringtype情况
2条回答

使用regex'(?<=Type: )[\w-]+'

  • (?<=Type: )将在类型之后提取所有内容:
  • [\w-]+将只提取数字单词-
import re
re.findall(r'(?<=Type: )[\w-]+',string)
>> ['2-A']

如果Type只包含一个数字“-”和一个字母,那么这将为您提供所需的结果

import re

string = 'Ph no. : 999999999 | year: 2021 | class no.: 10Type: 2-A | S-no. : dfwef | Name : dfwf'

type_str = re.search('(Type:\s\d+-\w+)', string).group()
print(type_str)

Type: 2-A

或者如果您只想提取2-A

import re

string = 'Ph no. : 999999999 | year: 2021 | class no.: 10Type: 2-A | S-no. : dfwef | Name : dfwf'

type_str = re.search('(Type:\s\d-\w)', string).group()
print(type_str.split(': ')[1])

2-A

最后,根据请求从Type:|提取任何文本,它将

import re

string = 'Ph no. : 999999999 | year: 2021 | class no.: 10Type: 10 X-ASFD 34 10 | S-no. : dfwef | Name : dfwf'

type_str = re.search('Type:\s(.*?\|)', string).group()
print(type_str.split(': ')[1].replace('|',''))

10 X-ASFD 34 10

相关问题 更多 >

    热门问题