Thread: Regex pattern

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

    Join Date
    Jun 2012
    Posts
    8
    Rep Power
    0

    Regex pattern


    What is the regex pattern which replace every word "car" with "bar" in the first set and the second does not?

    First:

    Code:
    car dog 680
    baby car bottle
    !@#$%^ car 987654
    WHISPER book car
    q  car ^&&* ;yu
    Second:

    Code:
    car dog 680 hh
    baby car bottle hh
    !@#$%^ car 987654 hh
    WHISPER book car hh
    q  car ^&&* ;yu hh
  2. #2
  3. Come play with me!
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,759
    Rep Power
    9397
    What? Do you want to replace car->bar or not?
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2012
    Posts
    8
    Rep Power
    0
    I want replace car with something (It's an example) but only if at the end there is no "hh".

    Effect should be like:

    Code:
    bar dog 680
    baby bar bottle
    !@#$%^ bar 987654
    WHISPER book bar
    q  bar ^&&* ;yu
    car dog 680 hh
    baby car bottle hh
    !@#$%^ car 987654 hh
    WHISPER book car hh
    q  car ^&&* ;yu hh
  6. #4
  7. Come play with me!
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,759
    Rep Power
    9397
    You can't do this with one expression: you'll need some code to back it.

    Since you need code,
    1. Grab a line
    2. If the line ends in "hh" then goto 1
    3. Replace every "car" with "bar"
    4. Goto 1 until you reach the end of the file
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2012
    Posts
    8
    Rep Power
    0
    Is it impossible to do it in one step (one pattern which exclude lines with "hh" at the end?)?
  10. #6
  11. Come play with me!
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,759
    Rep Power
    9397
    Well... no, on second thought you can. The problem is the possibility of there being more than one "car" on a line, but that's not necessarily a problem.

    Assuming PCRE,
    Code:
    /\bcar\b(?!.*hh$)/
    (\b is a word boundary, otherwise it would match "cartel" too)

    I just don't like doing replacements this way. It's valid, but it feels weird to me so I rarely ever consider it.

    Comments on this post

    • Black_Hat agrees
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2012
    Posts
    8
    Rep Power
    0
    Thank You very much!

IMN logo majestic logo threadwatch logo seochat tools logo