Got more questions? Find advice on: ASP | SQL | XML | Windows
in Search
Welcome to RegexAdvice Sign in | Join | Help

Problem with submatch

Last post 06-30-2009, 5:44 AM by mikefcooper. 3 replies.
Sort Posts: Previous Next
  •  06-29-2009, 5:22 AM 54410

    Problem with submatch

    I have a problem understanding why a submatch is performing the way it does. 

    Start with: {FIELDA}.getTime()-{FIELDB}-{EXISTING_UNITS_LOST}

    Apply this regex: (})([^\.]|$)

    Replace using: $1.toDoubleValue()

    Gives this: {FIELDA}.getTime()-{FIELDB}.toDoubleValue(){EXISTING_UNITS_LOST}.toDoubleValue()

    I want to replace all closing braces that don't already have a '.' after them witha '.toDoubleValue()' so I don't replace the } that already have a method attached, such as '.getTime().

    My expression tries to submatch on the '}' and then replace  just that using the '$1'. The problem is that the '-' after {FIELDB} disappears even though its outside the submatch.

    I use the brilliant RegExp tester at http://www.gskinner.com/RegExr/ to try expressions and I just can't get it to only replace the '}' and not the following 'non-dot' character as well.

    Any help much appreciated.

  •  06-29-2009, 10:32 AM 54421 in reply to 54410

    Re: Problem with submatch

    Raw Match Pattern:
    \}(?!\.)

    Raw Replace Pattern:
    }.toDoubleValue()

    $sourcestring after replacement:
    {FIELDA}.getTime()-{FIELDB}.toDoubleValue()-{EXISTING_UNITS_LOST}.toDoubleValue()
  •  06-29-2009, 10:40 AM 54423 in reply to 54410

    Re: Problem with submatch

    Two points.

    1) You seem confused by the replacement operation.  You can replace matches, not sub-matches.   You can use backreferences in your replacement but the entire pattern match is what is replaced.

    2) You don't need to escape a period in a character class.

    Raw Match Pattern:
    \}(?:(?!\.)|(?=$))

    Raw Replace Pattern:
    $0.toDoubleValue()

    $sourcestring after replacement:
    {FIELDA}.getTime()-{FIELDB}.toDoubleValue()-{EXISTING_UNITS_LOST}.toDoubleValue()

    Michael

    "In theory, theory and practice are the same. In practice, they are not."
    Albert Einstein
  •  06-30-2009, 5:44 AM 54438 in reply to 54423

    Re: Problem with submatch

    Hi Mash,

    Yes, I did think I could replace submatches as you suspected. 

    You're correct regex is fantastic and works perfectly - I would never have come up with that but will try and understand it so as to improve my regex skills.

     Thank you very much,

     Mike

View as RSS news feed in XML