SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Wizard lorenw's Avatar
    Join Date
    Feb 2005
    Location
    was rainy Oregon now sunny Florida
    Posts
    1,100
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Regex too greedy?

    Hi All,
    I'm trying to do a regex on a string, here is an excerpt,
    Code:
    ...},"end_address":"1901 SE Port St. Main  Blvd. Tampa, FL 34952","end_location" ...(data)... "end_location" ...(data)... "end_location"
    This is the part that I want to target "end_address":"1901 SE Port St. Main Blvd. Tampa, FL 34952","end_location" so I can replace the address.
    This is my regex
    Code:
    string = string.replace(/end_address.*end_location/, 'end_address":"1895 main street North","end_location');
    It works but the problem is that the regex spans all end_location (there should be many end_location) and wipes out a huge chunk of data, this leaves only one end_location.

    I just need to match the first occurrence of end_location and not the last occurrence of end_location.

    Thanks,
    Loren
    What I lack in acuracy I make up for in misteaks

  2. #2
    Utopia, Inc. silver trophy
    ScallioXTX's Avatar
    Join Date
    Aug 2008
    Location
    The Netherlands
    Posts
    9,070
    Mentioned
    153 Post(s)
    Tagged
    2 Thread(s)
    Isn't that JSON? If so, why not just use json_decode?
    Rémon - Hosting Advisor

    SitePoint forums will switch to Discourse soon! Make sure you're ready for it!

    Minimal Bookmarks Tree
    My Google Chrome extension: browsing bookmarks made easy

  3. #3
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,702
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    You can use ? to denote a non-greedy match, such as .*?
    Details about how it works are found at http://www.regular-expressions.info/repeat.html
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  4. #4
    SitePoint Wizard lorenw's Avatar
    Join Date
    Feb 2005
    Location
    was rainy Oregon now sunny Florida
    Posts
    1,100
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    @paul_wilkins Thank You, Thank You, Thank You, works a treat. Spent many hours on that.
    @ScallioXTX I am using JSON.stringify(response); Its for the google maps response so I have a string that I need to work with.

    Thanks to all.
    What I lack in acuracy I make up for in misteaks


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •