Search code examples
iphoneiosregexxcoderegexkit

How can I use regex to put quotes around a statement


I am using regexkitlite to validate some data in my iPhone app in xcode.

I am making an api call that sends a json result of:

"taskDate": newDate("September 23, 2011 00:00:00")

how do i use regex to convert it to:

"taskDate": "newDate("September 23, 2011 00:00:00")"

I want to surround the value of every "taskdate" key with quotes.

Edit: Adding OP's comment

Here is what i am using:

[resultString replaceOccurrencesOfRegex:@"new Date((.*?)\")," withString:@"\"\"," range:NSMakeRange(0, [resultString length])];

where resultString is the string containing the "new Date(...."


Solution

  • You can use regex to identify where in your text you have text in the format of "taskDate": "newDate("September 23, 2011 00:00:00")" but the actual replacement you will have to write yourself. Regex doesn't replace strings, it finds patterns within a string. Now, in order to find the pattern of "taskDate": newDate("<anything can go here>") you can use

    "taskDate"\: newDate\(".*?"\)
    

    If it is possible to have something else within the parenthesis, you will have to be more specific and only specify a date inside:

    "taskDate"\: newDate\("[a-zA-z]* \d{2}, \d{4} \d{2}\:\d{2}\:\d{2}"\)
    

    This will match everything of the sort of "taskDate"\: newDate\("Letters 00, 00:00:00"\). From here you can either make the months specific, and allow white space between all the quotations. All these changes makes the regex more complex, so only make it more strict to avoid matching things that you don't want. If no scenario exist that something else can be inside the parenthesis, I would go with the first regex.

    That said, after you match the string within your content, you need to write the code to surround it with the quotations.