简体   繁体   English

如何获取匹配substring的句子/字符串

[英]How to get the sentence / string with the matched substring

If the following content is given in a text file,如果在文本文件中给出以下内容,

Text1.txt文本1.txt

Registered: [10-01-21] Left: [12-02-21]已注册:[10-01-21] 已注册:[12-02-21]

Approved: [03-03-21] Name: Ann批准:[03-03-21] 姓名:安

Ann submitted documents.安提交了文件。 Ann checked [12-04-21]安检查 [12-04-21]


I need to get the output as :

Registered : [10-01-21]        
Left : [12-02-21]           
Approved : [03-03-21]       
checked [12-04-21]          

As the substring, we can give a regex to validate the date format.
import re
f1= open("Text1.txt")
string=f1.read()

found_p1=re.findall(r"(.*)\[[0-9]{2}[-][0-9][2][-][0-9]{2}\](.*)" ,string)
k=[ ]
for i in found_p1:
    i=re.sub(r"|',|'(|)", "", str(i))

try this:尝试这个:

import re

f = open("Text1.txt")
string = f.read()

pattern = re.compile("(\w+\s\[\d{2}[-]\d{2}[-]\d{2}\]|\w+\s[:][\s]\[\d{2}[-]\d{2}[-]\d{2}\])")
m = pattern.findall(string)
for i in m:
    print(i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用python在json类型的字符串中获取匹配的子字符串列表? - how to get matched substring list in a json-type string with python? 如何获得匹配的字符串 - How to get the matched string 检查字符串是否以子字符串元组开头并在python中获取匹配的字符串 - check if a string start with a tuple of substring and get the matched one in python 按照在原始句子中出现的顺序提取所有匹配的子字符串 - Extract all matched substring with the order as they appeared in the original sentence 从句子中的子字符串中的字符串中查找位置 - Find the position from a string in a substring in a sentence Python正则表达式:如何检查字符串中的字符是否在正则表达式匹配的子字符串的范围内? - Python regex: how to check if a character in a string is within the span of a regex matched substring? 如果子字符串重复,如何获取字符串中子字符串的周围单词? - How to get surrounding words of substring in string, if the substring repeats itself? 如何使用关键字或 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 提取句子前后的句子? - How to also extract sentence before and after sentence with keyword or substring? 如何从python中的字符串获取子字符串 - How to get the substring from a String in python 如何在最后一次出现子字符串之前获取字符串? - How to get String Before Last occurrence of substring?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM