3

I need a way to optimize by regex, here is the string I am working with:

rr='JA=3262SGF432643;KL=ASDF43TQ;ME=FQEWF43344;JA=4355FF;PE=FDSDFHSDF;EB=SFGDASDSD;JA=THISONE;IH=42DFG43;'

and i want to take only JA=4355FF which is before JA=THISONE, so i did it this way:

aa='.*JA=([^.]*)JA=THISONE[^.]*'
aa=re.compile(aa)
print (re.findall(aa,rr))

and i get:

['4355FF;PE=FDSDFHSDF;EB=SFGDASDSD;']

My first problem is slow searching apropriete part of string (becouse the string which i want to search is too large and usually JA=THISONE is at the end of string)

And second problem is i dont get 4355FF but all string until JA=THISONE.

Can someone help me optimize my regex? Thank you!

2 Answers 2

3

I. Consider using string search instead of regexes:

thisone_pos = rr.find('JA=THISONE')
range_start = rr.rfind("JA=", 0, thisone_pos) + 3
range_end = rr.find(';', range_start)
print rr[range_start:range_end]

II. Consider flipping the string and constructing your regex in reverse:

re.findall(pattern, rr[::-1])
Sign up to request clarification or add additional context in comments.

1 Comment

Can you give me solution with using string search on this example, key thing here for me is that i only take JA='4355FF' which is before JA=THISONE
1

You could consider the following solution:

import re

rr='JA=3262SGF432643;KL=ASDF43TQ;ME=FQEWF43344;JA=4355FF;PE=FDSDFHSDF;EB=SFGDASDSD;JA=THISONE;IH=42DFG43;'

m = re.findall( r"(JA=[^;]+;)", rr )

# Print all hits
print m

# Print the hit preceding "JA=THISONE;"
print m[ m.index( "JA=THISONE;" ) - 1]

First, you look for all instances starting with "JA;" and then, you pick the last instance located before "JA=THISONE;".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.