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

    Join Date
    Oct 2011
    Posts
    1
    Rep Power
    0

    Regex problem using replace method for outside area of the matching


    I got stick to a regex problem.

    I have a string, e.g.

    test foo bar [Hello] test foo X:123 foo bar

    The value inside the brackets and the brackets themselves must remain. Also the "X:" with the digits following must remain.
    The rest should be removed/replaced by using a regular expression.

    It may be that only a test in brackets OR the X:123 value appears in a search string.

    Using the replace method of the following regular expression it nearly works:
    [^\[^\]](?=[^\]]*?(?X:\[|$))

    Has anyone an idea how to connect both possibilities (to remain the value in brackets and/or the substring with X:<some digits>)
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    14,072
    Rep Power
    9398
    Does the thing in brackets always come before the X:digits?
    Code:
    Replace
    /.*?((\[.*?\])(.*?(X:\d+))?|(X:\d+)).*/
    with
    $2$4$5
    which leaves you with
    Code:
    [Hello]X:123

IMN logo majestic logo threadwatch logo seochat tools logo