By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,213 Members | 1,966 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,213 IT Pros & Developers. It's quick & easy.

Getting the start / end of string in regex through match objects

P: n/a
I want to get the start and end of all the patterns mattched in regex.
I know I can get it with start() and end() fn of matched objects. But
re.search() return the match object of first matching regex in the
string. I want all match objects in that string

Here is the string :

tmplstr = """
${name}

${list:parentlst}
an element ${elem:parentlst}
${/list:parentlst}

${list:childlst}
an element ${elem:childlst}
${/list:childlst}
"""

Here is the regex script:

# Compile List Patterns
# Start of List
lstpattern_st = r"(\$\{list:([a-z]*[0-9 ]*)\})"
lstpat_st = re.compile(lstpattern_st)

# End of List
lstpattern_end = r"(\$\{/list:([a-z]*[0-9 ]*)\})"
lstpat_e = re.compile(lstpattern_end, re.I)
matchgrp_st = lstpat_st.search(tmplstr)
strt = matchgrp_st.start()
print strt
matchgrp_e = lstpat_e.search(tmplstr)
end = matchgrp_e.end()
print end
print self.tmplstr[strt:end]

I want all the start and end indices of the string but re.search()
returns the first regex met in the string. re.match() also wont work
because it search in the begining.

Can anyone help me in getting the start and end indices of all. OR can
provide any other solution instead of this

Jan 9 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
"ankit" wrote:
I want to get the start and end of all the patterns mattched in regex.
I know I can get it with start() and end() fn of matched objects. But
re.search() return the match object of first matching regex in the
string. I want all match objects in that string


for m in re.finditer(pattern, string):
print m.start(), m.end()

(or use the start offset to re.search)

</F>

Jan 9 '06 #2

P: n/a
Thanks frederik, :)

Jan 10 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.