#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2005
    Location
    NIPPON
    Posts
    15
    Rep Power
    0

    regular expression like sed


    Can python alllow you to write expression like sed does ?
    Example

    test = s/(this)is(who)/\2 is \1/
  2. #2
  3. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    588
    Rep Power
    64

    Smile


    What is the result?
    Why would anyone like to write something that cryptic?
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    Originally Posted by oppai
    Can python alllow you to write expression like sed does ?
    Example

    test = s/(this)is(who)/\2 is \1/
    Yes it can. There is a regex module called re, so it is not quite as convenient as languages that have regex built into the core language, but IMHO is more powerful.

    The python equivalent is

    Code:
    >>> import re
    >>> s = 'this is who'
    >>> re.sub( r'(this) is (who)', r'\2 is \1', s)
    'who is this'
    >>>
    Dave - The Developers' Coach
  6. #4
  7. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    588
    Rep Power
    64

    Smile


    Thanks,
    now it makes sense. I am learning.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2004
    Posts
    461
    Rep Power
    24
    with python, you also don't have to use re's they are very cryptic and hard to read. I personly do not like them. You can write something like this instead in python that is built into the language.

    Code:
    >>> s = "this is who"
    >>> sp = s.split()
    >>> end = sp[2] + " " + sp[1] + " " + sp[0]
    >>> print end
    who  is this

    now that is a lot easyer to read and it does the same exact thing. I know there are better ways to do this, sorry it is like 3 in the morning and that was the first way that came to my head. I hope I got the re translation right, I havn't played with them in ever.

IMN logo majestic logo threadwatch logo seochat tools logo