简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM