如何在文本中查找字符串并从文本中返回字符串?

2024-04-24 14:05:05 发布

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

我需要找到一个已经去掉特殊字符的字符串。所以,我想做的是在一个句子中找到这个字符串,并返回带有特殊字符的字符串。 例如:string = France09

Sentence : i leaved in France'09.

现在我做了re.search('France09',sentence),它将返回TrueFalse。但是我想得到输出为France'09。你知道吗

有人能帮我吗。你知道吗


Tags: 字符串inrefalsetruesearchstringsentence
3条回答

从文档(https://docs.python.org/2/library/re.html#re.search)中,搜索不是返回TrueFalse

Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

试试这个:

Input_str = "i leaved in France'09"

Word_list = Input_str.split(" ")
for val in Word_list:
    if not val.isalnum():
        print(val)

输出:

France'09

看看https://regex101.com/r/18NJ2E/1

TL;博士

import re

regex = r"(?P<relevant_info>France'09)"
test_str = "Sentence : i leaved in France'09."
matches = re.finditer(regex, test_str, re.MULTILINE)
for match in matches:
    print(match.group('relevant_info'))

相关问题 更多 >