user3525290
user3525290

Reputation: 1607

Regex Python questions

Regex help. I am searching a string and looking to find and remove text. What I have so far is not working.

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 a I get none.
What I am looking for help with is how do I find the line findme= and remove the entire line from the string and save the line to a variable to be used later. As well as removing the line from the string.

Upvotes: 4

Views: 127

Answers (3)

Keerthana Prabhakaran
Keerthana Prabhakaran

Reputation: 3787

Your regex needs to search for a group that starts with findme= and the any character or number.

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

I suggest you to use re.sub if you want to find and replace string(change_to) from your 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'

Upvotes: 1

zipa
zipa

Reputation: 27869

If you want to import re 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]

Upvotes: 1

L3viathan
L3viathan

Reputation: 27273

You don't 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)

This results in:

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

Upvotes: 2

Related Questions