Terik Brunson
Terik Brunson

Reputation: 187

Creating a Regex That Applies to multiple lengths of strings and characters

PLAY [[B2 C3# D3 D3# ]]
PLAY [[A1 A1# B1 D1# E1 F1 F1# G1 A2 B2 F2# G2 C3 C3# D3 D3# ]]

I need to create a regex (with the ultimate purpose of removing "PLAY" and "[[]]" from all lines of a text file. The insides of the brackets will vary with each line, so how do I create a regex match pattern to return only the group within the brackets for each line?

Any help is appreciated, I'm kind of a noob with this.

Upvotes: 0

Views: 48

Answers (2)

alecxe
alecxe

Reputation: 473863

Since you know the start and end strings and their lengths, just slice the part you need:

>>> s = "PLAY [[A1 A1# B1 D1# E1 F1 F1# G1 A2 B2 F2# G2 C3 C3# D3 D3# ]]"
>>> s[7:-3]
'A1 A1# B1 D1# E1 F1 F1# G1 A2 B2 F2# G2 C3 C3# D3 D3#'

Upvotes: 5

Avinash Raj
Avinash Raj

Reputation: 174706

Use re.sub

for line in file_obj:
    print re.sub(r'.*\bPLAY\s*\[\[(.*?)\]\].*', r'\1', line)

Upvotes: 1

Related Questions