how to format a return value by using re.sub(regx,rep1,str)?

D

dongdong

for example:
re.sub('<a( [^>]+)+\s?>[^<^>]*</a>','',' asd ga<a target="_blank"
href="http://www.sine.com" class="wordstyle"> asdgasdghae rha</a>')

I wish to get the return value "asd ga asdgasdghae rha",how do do?
I have a impression on "%" and "{number}",but forgot how to use them.
 
K

Kent Johnson

dongdong said:
for example:
re.sub('<a( [^>]+)+\s?>[^<^>]*</a>','',' asd ga<a target="_blank"
href="http://www.sine.com" class="wordstyle"> asdgasdghae rha</a>')

I wish to get the return value "asd ga asdgasdghae rha",how do do?
I have a impression on "%" and "{number}",but forgot how to use them.
Use a group to capture the text between <a> and </a>:

In [10]: re.sub('<a( [^>]+)+\s?>([^<^>]*)</a>',r'\2',' asd ga<a
target="_blank" href="http://www.sine.com" class="wordstyle">
asdgasdghae rha</a>')
Out[10]: ' asd ga asdgasdghae rha'

Kent
 
P

Paul McGuire

dongdong said:
for example:
re.sub('<a( [^>]+)+\s?>[^<^>]*</a>','',' asd ga<a target="_blank"
href="http://www.sine.com" class="wordstyle"> asdgasdghae rha</a>')

I wish to get the return value "asd ga asdgasdghae rha",how do do?
I have a impression on "%" and "{number}",but forgot how to use them.

Well, here's the pyparsing rendition (two, actually). I hope it's easier to
follow then trying to pick apart the above regexp. Both

Download pyparsing at http://pyparsing.sourceforge.net.

-- Paul


instr = """' asd ga<a target="_blank"
href="http://www.sine.com" class="wordstyle"> asdgasdghae rha</a>'"""

from pyparsing import makeHTMLTags,Suppress,MatchFirst

# makeHTMLTags returns a tuple of the start and end pattern for the given
tag
aStart,aEnd = makeHTMLTags("a")

# define a filter that will suppress the opening and closing tags
# this is easily extended to filter additional patterns, too
filter = Suppress(aStart) | Suppress(aEnd)

# invoke transformString using the filter
print filter.transformString(instr)

# or for the dense-code minded...
filter = MatchFirst( map( Suppress, makeHTMLTags("a") ) )
print filter.transformString(instr)


Prints:
' asd ga asdgasdghae rha'
' asd ga asdgasdghae rha'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top