简体   繁体   中英

Grep a string in python

Friends,

I have a situation where i need to grep a word from a string

[MBeanServerInvocationHandler]com.bea:Name=itms2md01,Location=hello,Type=ServerRuntime

What I want to grep is the word that assigned to the variable Name in the above string which is itms2md01 .

In my case i have to grep which ever string assigned to Name= so there is no particular string i have to search

Tried:

 import re
 import sys

 file = open(sys.argv[2], "r")

 for line in file:
        if re.search(sys.argv[1], line):
              print line,

Deak is right. As I am not having enough reputation to comment, I am depicting it below. I am not going to the file level. Just see as an instance:-

import re

str1 = "[MBeanServerInvocationHandler]com.bea:Name=itms2md01,Location=hello,Type=ServerRuntime"

pat = '(?<=Name=)\w+(?=,)'

print re.search(pat, str1).group()

Accordingly you can apply your logic with the file content with this pattern

I like to use named groups, because I'm often searching for more than one thing. But even for one item in the search, it still works nicely, and I can remember very easily what I was searching for.

I'm not certain that I fully understand the question, but if you are saying that the user can pass a key to search the value for and also a file from which to search, you can do that like this:

So, for this case, I might do:

 import re
 import sys

 file = open(sys.argv[2], "r")

 for line in file:
     match = re.search(r"%s=(?P<item>[^,]+)" % sys.argv[1], line)
     if match is not None:
         print match.group('item')

I am assuming that is the purpose, as you have included sys.argv[1] into the search, though you didn't mention why you did so in your question.

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