Questions in Regex Python

Regular expression help. I am looking for a string and am looking to find and delete text. That I still do not work.

thisstring = "some text here
more text
findme=words15515.1515
"
a = re.compile(r'^findme=\.*')
a = a.search(thisstring)

I want to find and copy the entire line.

When I print, I do not get a single one. I am looking for help on how to find findme = string and remove the entire string from the string and save the string in a variable that will be used later. Also remove the line from the line.

+4
source share
3 answers

You do not need regex:

thisstring = """some text here
more text
findme=words15515.1515
"""

not_matching, matching = [], []
for line in thisstring.split("\n"):
    if line.startswith("findme="):
        matching.append(line)
    else:
        not_matching.append(line)
new_string = '\n'.join(not_matching)

It leads to:

>>> new_string
'some text here\nmore text\n'
>>> matching
['findme=words15515.1515']
+2
source

If you want to import again, this is one way:

import re

thisstring = '''some text here
more text
findme=words15515.1515
'''
a = [t[0] for t in [re.findall(r'^findme=.*',r) for r in thisstring.split('\n')] if t]
+1
source

, findme= .

>>> a = re.compile(r'.*(findme=.*\n?)')
>>> a = a.findall(thisstring)
>>> print a
['findme=words15515.1515']

re.sub, (change_to) thistring

>>> change_to =''
>>> thisstring
'some text here\nmore text\nfindme=words15515.1515'
>>> re.sub(r'findme=.*\n?',change_to,thisstring)
'some text here\nmore text\n'
+1

Source: https://habr.com/ru/post/1673326/


All Articles