Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Parsing string option that might or might not have quotes

    I'm trying to implement option handling that mirrors the behavior of graph options like title(): If the option has an unquoted multiword string, it is treated as a single string. If a multiword string is put into the option surrounded by quotes, the quotes are stripped off and it is treated as a single string. If two quoted strings are put into the option, they are treated as separate strings.

    I can achieve this with the following, which wraps the option in a set of compound-quotes before parsing it, IF it is not already wrapped in quotes, but I'm wondering if there is a more elegant approach I'm missing:

    Code:
    program myprog
        version 15
        syntax , [ notes(string asis) ]
    
        // feels like a hack
        if !strpos(`"`notes'"',`"""') {
            local notes `"`"`notes'"'"'
        }
    
        tokenize `"`notes'"'
        while !missing(`"`1'"') {
            di `"A note: [`1']"'
            macro shift
        }
    end
    This does what I want

    Code:
    . myprog , notes("This is the first note" "This is a second note")
    A note: [This is the first note]
    A note: [This is a second note]
    
    . myprog , notes("This is a single quoted note")
    A note: [This is a single quoted note]
    
    . myprog , notes(This is a single note)
    A note: [This is a single note]

  • #2
    Use 'string' instead of 'string asis' ? The help file mentions: " asis specifies that the option's arguments be returned just as the user typed them, with quotes (if specified) and with leading and trailing blanks. asis should be specified if the option's arguments might contain suboptions or expressions that contain quoted strings. If you specify asis, be sure to use compound double quotes when referring to the macro."

    Consider:

    Code:
    cap program drop myprog
    program myprog
        version 15
        syntax , [ notes(string asis) test(string)]
        di `"1: `notes'"' as error
        di in y `"2: `test'"'
    
    end
    
    
    myprog  ,  notes("Test") test("Test")
    myprog  ,  notes(`"Test"') test(`"Test"')
    myprog  ,  notes("Test" "Test2" ) test("Test" "Test2")
    myprog  ,  notes(`"Test"' `"Test2"' ) test(`"Test"' `"Test2"')
    myprog  ,  notes(`"`"Test"' `"Test2"' "') test(`"`"Test"' `"Test2"'"')
    (Maybe I'm missing the point of your question though?)
    Eric A. Booth | Senior Director of Research | Far Harbor | Austin TX

    Comment

    Working...
    X