[SOLVED] Need a regex to find a string using python .
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
import re
with open('test.txt') as f:
text = f.read()
print re.findall('>(TX-[0-9]{4})<', text)
That said, did you consider fixing the XML file so that it's proper XML, and then using an XML parser? The Python standard library includes one. Most people would use lxml.
That re code helped quickly to resolve the issue . Can u explain what it it doing really the below code .
re.findall('>(TX-[0-9]{4})<', text)) .
Thanks and regards
Well, I assume you can look up what "re.findall" does. Don't dispel that assumption.
I saw that all of the instances you wanted were ">TX-####<". Tag-closing angle bracket, "TX-" constant, 4 numbers, tag-opening angle bracket. So we're searching for strings between ">" and "<". Hence: ">(...)<". The parenetheses specify a group, and what's inside the group will be found. So inside the group, I have "TX-". That's a constant. Followed by "[0-9]", a digit, followed by "{4}", repeated 4 times.
See how unwise it is to ask someone to "explain" a regular expression?
EDIT: it's unwise because it's really difficult to explain them in a way that's easy to follow and that doesn't come off as word salad.
Last edited by dugan; 12-24-2015 at 12:57 PM.
Reason: The last line needed an explanation
Many thank for the explanation . We are using {4} which will search numbers repeated 4 times only. It wont work if number repeated 5 times e.g.(TX-12345) . Is there any way we can search
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.