regular expressions

  • Thread starter krishnamanenianil
  • Start date
J

J. Clifford Dyer

hi i am looking for pattern in regular expreesion that replaces
anything starting with and betweeen http:// until /
like http://www.start.com/startservice/yellow/ fdhttp://helo/abcd will
be replaced as
p/startservice/yellow/ fdp/abcd

You don't need regular expressions to do that. Look into the methods that strings have. Look at slicing. Look at len. Keep your code readable for future generations.

Py>>> help(str)
Py>>> dir(str)
Py>>> help(str.startswith)

Cheers,
Cliff
 
P

Paul McGuire

You don't need regular expressions to do that. Look into the methods that strings have. Look at slicing. Look at len. Keep your code readable for future generations.

Py>>> help(str)
Py>>> dir(str)
Py>>> help(str.startswith)

Cheers,
Cliff

Look again at the sample input. Some of the OP's replacement targets
are not at the beginning of a word, so str.startswith wont be much
help.

Here are 2 solutions, one using re, one using pyparsing.

-- Paul


instr = """
anything starting with and betweeen "http://" until "/"
like http://www.start.com/startservice/yellow/ fdhttp://helo/abcd
will
be replaced as
"""

REPLACE_STRING = "p"

# an re solution
import re
print re.sub("http://[^/]*", REPLACE_STRING, instr)


# a pyparsing solution - with handling of target strings inside quotes
from pyparsing import SkipTo, replaceWith, quotedString

replPattern = "http://" + SkipTo("/")
replPattern.setParseAction( replaceWith(REPLACE_STRING) )
replPattern.ignore(quotedString)

print replPattern.transformString(instr)


Prints:

anything starting with and betweeen "p/"
like p/startservice/yellow/ fdp/abcd will
be replaced as


anything starting with and betweeen "http://" until "/"
like p/startservice/yellow/ fdp/abcd will
be replaced as
 

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
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top