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

    Join Date
    Oct 2011
    Posts
    7
    Rep Power
    0

    Regex Replace Word Between 2 Characters


    Hi guys I need help with this reg ex:

    I want to search for every word between:
    / and _ and have everything between removed (except the backslash)

    Example
    /horse_farm
    Result
    /farm

    I tried this
    /.*?_
    But the problem is that if there is
    /village/horse_farm
    I get
    /farm instead of /village/farm
    I only want the removal to start from the last backslash not every back slash before it as well. So the correct result for the last example should be
    /village/farm

    I appreciate any help. Thanks
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,997
    Rep Power
    9397
    What language are you using? If it's PCRE-compatible then
    Code:
    #(?<=/)[^/_]+_#
    (?<=/) finds a slash and starts the expression immediately after while [^/_]+ matches a bunch of non-slash, non-underscore characters.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2011
    Posts
    7
    Rep Power
    0
    Thanks for the response. I tried the code but it didn't work. I'm using Emeditor. I actually did it in a different way, thanks though

    Originally Posted by requinix
    What language are you using? If it's PCRE-compatible then
    Code:
    #(?<=/)[^/_]+_#
    (?<=/) finds a slash and starts the expression immediately after while [^/_]+ matches a bunch of non-slash, non-underscore characters.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Posts
    830
    Rep Power
    496
    Hi,

    this is how I would do it in Perl:

    Code:
    s/\/[^_\/]*_/\//g;
    or (using parens or semi-colon as separator rather than / to avoid escaping):

    Code:
    s(/[^_\/]*_)(/)g;
    or 
    s;/[^_\/]*_;/;g;
    For example, if you have the following string: "/foo/bar_baz/", these regexes will return this: "/foo/baz/", which is what you want, as far as I understand.

    I leave it to you to adapt to your specific regex package, which I do not know.

IMN logo majestic logo threadwatch logo seochat tools logo