Liliana
Liliana

Reputation: 11

Find a pattern and line of file using python

I have a file.txt which contains lines as:

address1:= ("a010")
address2:= ("b005")
address3:= ("b030")
address4:= ("b008")
address5:= ("a002")
address6:= ("b004")

I need to match only the number followed by "b" as well as its line as:

2: 005
3: 030
4: 008
6: 004 

Anybody can help me to do that using python?

Upvotes: 0

Views: 43

Answers (2)

Jorge Omar Medra
Jorge Omar Medra

Reputation: 988

Use this expression and capture the group 1:

(?:[b])([0-9]{3})

Here is a sample:

https://regex101.com/r/fL4csm/2

In the case of using python, i suggest you to try to add some code that you coded instead of asking for how to code it. Check this link:

https://stackoverflow.com/help/on-topic

Upvotes: 1

Sharad
Sharad

Reputation: 10592

Code snippet:

foo = """
address1:= ("a010")
address2:= ("b005")
address3:= ("b030")
address4:= ("b008")
address5:= ("a002")
address6:= ("b004")
"""
import re
pattern = 'address(\d+):= \("b(.*)"\)'
result = re.findall(pattern, foo)
for item in result:
    print('{index}: {entry}'.format(index=item[0], entry=item[1]))

Execution Output:

2: 005
3: 030
4: 008
6: 004

Upvotes: 3

Related Questions