Lua function to replace metatags in a string?

(Maybe this is a recipe request for the new cookbook site.)
I'd like a function that, given a string and a LrPhoto, will search and replace tags in the string with metadata from the photo. So, given a string 'The title of this photo is {{title}}', it would return a string where {{title}} has been replaced with the LrPhoto.getRawMetadata('title') (or maybe getFormattedMetadata). I'm sure it's been written more than once. Is there one out there to be shared before I write my own?
db

I spent the time on this myself and don't know why I bothered asking, it was so simple. Here's what I did. First, a general-purpose function to replace any token in a string with values from a table:
-- replace any string of characters in a string that are surrounded by curly
-- braces (e.g. {foo}) with the value in the table corresponding to 'foo'.
-- will replace all tokens in braces if there are more than one
function DFB.replaceTokens( tokenTable, str )
    return str:gsub( '{(.-)}', function( token ) return tokenTable[token] end )
end
Then, if you want to do this with a photo's metadata, just pass the table that's returned from getRaw/FormattedMetadata:
line = DFB.replaceTokens(  photo:getFormattedMetadata( nil ) , line )
So if line starts out with "my caption is {caption}" and the photo's caption is 'My Photo Caption', the result is "my caption is My Photo Caption".
I use this in a simple templating system that reads an HTML template from a file and does this for each line as it reads/writes it. Works well.

Similar Messages

  • REPLACE exact match in string

    Hi,
    I am using SQL Server 2008 R2 Standard Edition. My question is:
    How to use the REPLACE function (or any other T-SQL function if you have a better suggestion than the REPLACE function) to replace an
    exact match in a string? For instance, let's say I have this string:
    'success and successfully'. I would like to change the word "success" to "failure"
    without changing the word "successfully" to "failurefully". This is exactly what happens when the function REPLACE is used. 
    REPLACE('success and successfully', 'success', 'failure')
    How to force an exact match?
    Thank you!

    I thank all of you for your interesting and clever answers. I believe each one of them can be applied depending on the situation. In my case, I have found a practical and simple solution to my own problem.
    The bulk of the problem with T-SQL "REPLACE" function arises when a word is a subset of another word in the initial string. In my example, "success" is a
    subset of "successfully" in the initial string "success and successfully".
    To simulate an exact match with the "REPLACE" function, just include in both the
    replaced string and in the
    replacer string the first extra character that causes a difference between the word and its subset. In my example, the space after the subset "success" constitute the breaking character from the word "successfully". Thus, the
    code becomes (note the space after both "success" and "failure"):
    REPLACE('success and successfully', 'success ', 'failure ')
    The expected output result is: failure and successfully
    This simple technique works in all other situations where the extra character does not have to be a space; any breaking point character will work fine.
    Thank you again to all of you for pitching in!
    LOL... this wont work in some situations.
    Imagine if you have a string like 'Successfully and success.'. You will have to add an additional replace function. And if your string equals to the replaced word, such as in 'success', it won't work either.

  • How to use replace function to replace word

    I am trying to write a replace function in which I replace CA with California in an address string.
    I am trying to avoid using regular expression and just use other functions like replace, instr, trim etc.
    But what my main confusion is how do i take care of three cases in which.
    CA can be present with spaces before and after it like.
    - Redwood City, CA 96403
    CA can be present with spaces only before it and after it the string ends.
    - Redwood City, CA
    and I do not want to replace any other CA in the string that is part of other word
    - Blaca Street CA
    ( for example do not replace ca in Blaca)
    or
    - Cardinal Dr CA
    Thanks

    Hi,
    user6287828 wrote:
    ... (only four of these abbreviations need to be replaced)In that case, nesting the functions one inside another won't be too bad. But watch out: this is exactly the kind of requirement that changes over time. You might only need 4 states now, nut next year they might expand the application so that you need all 50 states (plus Puerto Rico, and DC, and ....). In that case, something like MODEL, or a user-defined PL/SQL function, would be better.
    As these are abbreviations these will always be stand alone words and never part of words. And these abbreviation can be at the beginning or end or in between the string.
    And any abbreviation can be present in one column.
    More than one abbreviation can be present in one column
    None of the abbreviations can be present in this column.
    For example
    column
    3251 BLACA ROAD CA 94305
    74 CALDWIN STREET CA
    67 DIGITAL DRIVE NM
    NM UNIVERSITY AVENUE 890
    7645 ROCHESTER NY PARK STREET
    834 GRAND AVENUE ATLANTAPost CREATE TABLE and INSERT statements for the sample data.
    Include all special cases, e.g. more that one abbreviation in the same column.

  • Find and replace value in Delimited String

    Hi All,
    I have a requirement, where i need to find and replace values in delimited string.
    For example, the string is "GL~1001~157747~FEB-13~CREDIT~A~N~USD~NULL~". The 4th column gives month and year. I need to replace it with previous month name. For example: "GL~1001~157747~JAN-13~CREDIT~A~N~USD~NULL~". I need to do same for last 12 months.
    I thought of first devide the values and store it in variable and then after replacing it with required value, join it back.
    I just wanted to know if there is any better way to do it?

    for example (Assumption: the abbreviated month is the first occurance of 3 consecutive alphabetic charachters)
    with testdata as (
    select 'GL~1001~157747~FEB-13~CREDIT~A~N~USD~NULL~' str from dual
    select
    str
    ,regexp_substr(str, '[[:alpha:]]{3}') part
    ,to_date('01'||regexp_substr(str, '[[:alpha:]]{3}')||'2013', 'DDMONYYYY') part_date
    ,replace (str
             ,regexp_substr(str, '[[:alpha:]]{3}')
             ,to_char(add_months(to_date('01'||regexp_substr(str, '[[:alpha:]]{3}')||'2013', 'DDMONYYYY'),-1),'MON')
    ) res
    from testdata
    STR
    PART
    PART_DATE
    RES
    GL~1001~157747~FEB-13~CREDIT~A~N~USD~NULL~
    FEB
    02/01/2013
    GL~1001~157747~JAN-13~CREDIT~A~N~USD~NULL~
    with year included
    with testdata as (
    select 'GL~1001~157747~JAN-13~CREDIT~A~N~USD~NULL~' str from dual
    select
    str
    ,regexp_substr(str, '[[:alpha:]]{3}-\d{2}') part
    ,to_date(regexp_substr(str, '[[:alpha:]]{3}-\d{2}'), 'MON-YY') part_date
    ,replace (str
             ,regexp_substr(str, '[[:alpha:]]{3}-\d{2}')
             ,to_char(add_months(to_date(regexp_substr(str, '[[:alpha:]]{3}-\d{2}'), 'MON-YY'),-1),'MON-YY')
    ) res
    from testdata
    STR
    PART
    PART_DATE
    RES
    GL~1001~157747~JAN-13~CREDIT~A~N~USD~NULL~
    JAN-13
    01/01/2013
    GL~1001~157747~DEC-12~CREDIT~A~N~USD~NULL~
    Message was edited by: chris227 year included

  • Need a function module to convert xstring to string in web dynpro applicati

    hi,
       need a function module to convert xstring to string in web dynpro application other than HR_KR_XSTRING_TO_STRING.
    Moderator message: please (re)search yourself first.
    Edited by: Thomas Zloch on Nov 17, 2010 5:31 PM

    Hi,
    Check the following link:
    FM to convert XString to String
    Regards,
    Bhaskar

  • Creating a Function module to send XML Byte String

    Hi all,
    I have to create a Function module to get XML byte string.The internal table is dynamic coloums based on how many data selected as a importparameter.from the internal; table data I have to create a XML byte string as a output.Pl help me to proceed further.
    Thanks in Advance.
    Ram

    If i have your question right you need to convert an internal table of unknown type to an xml string then to a byte string.
    data xmlString type string.
    data xmlXString type xstring.
    call transformation id
       source
          table = internalTableYouWantToExport
       result
          xml xmlString.
    export xmlString to data buffer xmlXString.
    xmlString has the xml of the table and xmlXString contains the byte representation of the string.

  • Obselete function module replacement in ECC 6.0

    Hi SDN,
    Pls let me know the replacement for FM GRAPH_SET_CUA_STATUS. in ECC 6.0.
    Regards,
    Rahul Wagh

    Hi Rahul,
    in [this blog |/people/andrea.olivieri/blog/2010/04/30/community-call-obsolete-function-modules-replacement-matrix-for-ecc-60]published several months ago, I collected my thoughts on this persistent issue.
    In my opinion you can continue to use the FM GRAPH_SET_CUA_STATUS without any problems, confirming that the presence of numerous standard programs that use this method.
    Regards,
    Andrea

  • Global User Functions not replaced in Check Contraint

    Hi all,
    we just moved from ODI 11.1.7 to ODI 12.1.2 an have the following problem. Our global user functions which are used in several Check Conditions are no longer replaced during code generation.
    They worked like a charm in ODI 11.1.7. Any ideas?
    Kind regards,
    Jens

    We are running Scenarios and Mappings from Designer using Local and Remote Agents (Simulation and Execution Mode). No difference at all.
    Global User Functions are replaced in Filters and Target Expressions but not in ODI Constraints.

  • Replacing 'word' in a string

    Hi! I want to replace Strings in a String, but if the the substring which has to be replaced is not a word, then i don't want it to be replaced. Eg.: I want to replace Words for other strings, where words are not substring of other Words :)
    Just want to ask if someone has made this before, and can help me out
    cu
    athalay

    But, my original question wasn't this. I
    want to replace words(string) for other strings in
    sentences(string). I hope it's clearer. So for example
    I have a sentence: This is an applepie. And if I want
    to replace apple for pear, then do not replace this
    sentence for pearpie, just remain it, because there's
    no "apple" word in this sentence. I hope it's clearer.
    My main problem is, that handling the First word of
    the sentence. It easy to replace " "+word+" " for what
    I want, but there are separatorchars like , . etc :)Search for the word you want to replace. Once you have found it, you will need to do a series of other checks...
    1) is it at the beginning or end of the sentence? (then you need to look at the character before or after the word depending on location in entire String to see if it is whitespace or separator character)
    2) is it surrounded by whitespace or separator characters on both sides? (get the surrounding characters and compare to a list of acceptable characters to make this a word, ie " ", ",", ";"...
    Only replace words that pass the conditions (beginning of sentence and followed by whitespace or separator, end of sentence and preceeded by whitespace or separator, or middle of sentence and surrounded by whitespace or separators).

  • How to use replace(CharacterSequence, CharacterSequence) in String class

    Need simple java program using the following
    how to use replace(CharacterSequence, CharacterSequence) in String class
    Kindly help

    From http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#replace(java.lang.CharSequence,%20java.lang.CharSequence)
    replace
    public String replace(CharSequence target,
    CharSequence replacement)Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".
    Parameters:
    target - The sequence of char values to be replaced
    replacement - The replacement sequence of char values
    Returns:
    The resulting string
    Throws:
    NullPointerException - if target or replacement is null.
    Since:
    1.5

  • CS3: grep search to replace part of a string

    Can I do a grep search for a string of text but only replace a portion of the string while leaving the remainder intact?
    iMac G5, OS 10.5.5

    In addition to Eric:
    Find "some search string", Replace "some replacement string " also replaces part of the string, not touching anything...
    But the GREP search has two advantages: First, if you define formatting in the Replace field (italics, superscript, a character style), only the 'search'/'replacement' part will be affected, rather than the entire found string (as in regular search).
    The second big advantage is you can use any regular GREP single character wildcard in the 'left' and 'right' (matching-but-not-marking) parts. A few useful examples: '\d' (digit), '\l' and '\u' (lowercase and uppercase), '.' (any character), or even '[a-f]' (lowercase 'a' to 'f'). The only limitation is that you cannot use the once, zero-or-more, or once-or-more modifiers -- the strings must have a fixed length. FYI, those three modifiers are, respectively, ?, *, and +.
    This restriction does not apply to the 'middle' string, the one you are going to replace anyway -- use whatever GREP you want.

  • Replace frist in html string

    Hi Guys,
    I have an html string defined in property file.<html>,,,,,,<body>,,,,,blah blah $1 blah blah .........</html>
    I have html and eg $1, $2 so on.
    I want to replace $1 with another string value in the program, I tried str.replaceFirst("\\$1",string);
    but didnt work,
    please help me replcing it,
    thanks,

    DrClap wrote:
    It didn't work because that method takes a regular expression as its first parameter. (The API documentation does mention that fact.) The regular expression you passed it ("$1") ...The OP did escape the $, but &#92;&#92; get eaten by the forum software as a new-line char.
    @OP, the replaceFirst(...) returns a new String (and does not change the original String!), so you will have to do:
    String s = "<html>,,,,,,<body>,,,,,blah blah $1 blah blah .........</html>";
    s = s.replaceFirst("\\$1", "XYZ");

  • Function to replace/delete specific character(s) in a string

    Hi, experienced CVI guys,
    Are there some functions shipped with CVI to replace or delete specific characters in a string?
    For example, I want to replace all \/|- with an empty string, or to delete them. What can I do?  Loops are too complex.
    Original string:
    Erasing Device...
    \|/- \ \ \\|/-\|/ \
    Report
    07-Sep-2010, 08:04:55
    Result I want is
    Erasing Device...
    Report
    07-Sep-2010, 08:04:55
    Thanks.
    Solved!
    Go to Solution.

    labc:
    How generic do you want to make your filter?
    For our discussion, I'll call your series of characters a text spinner.  I'm assuming the number of characters in it may vary, but that the pattern is consistent in the respect: the spinner is made up of characters like \ / | -, each followed by the ASCII backspace (char) 8.  (That's 8 cast as a character, which is not the same as '8'.)  In your sample spinner pattern, every occurrence of the ASCII backspace is preceded by one of the spinner characters.  Let's assume that this pattern is constant.
    So what I'd do is search through your input string (yes, using a loop) and copy the input string byte by byte to an output string.  If you find an ASCII backspace in the input string, skip it, and overwrite the last character in the output string (which is one of the spinner characters) with the next character in the input string.
    Yes, you are using a loop, but it's not too complex.
    Here's the whole loop, written as a function.
    // filterSpinner function to strip the text spinner characters out of a string.
    // The text spinner is made up of \ / | - characters separated by (char) 8 (ASCII backspace)
    int filterSpinner(char *inputString, char *outputString)
     int inputPtr, outputPtr = 0;
     // walk though the input string
     for (inputPtr = 0; inputPtr < strlen(inputString); inputPtr++, outputPtr++)
      // search for the ASCII backspace character that's part of the spinner
      if (inputString[inputPtr] == 8)
       // if the ASCII backspace is found,
       inputPtr++;  // increment the inputString pointer to skip the backspace
       outputPtr--; // decrement the outputString pointer to overwrite
           // the spinner character that preceded the backspace
      outputString[outputPtr] = inputString[inputPtr];
     outputString[outputPtr] = '\0';
     return 0;
    You'll also find an attached CVI program which uses it on your sample string.
    Attachments:
    FilterSpinner1.zip ‏5 KB

  • Edit Field Validation - Use of the native string.find() Lua Function

    Hi,
    I have an edit field in which I want to be validated immediately upon change.  I ONLY want to accept alphanumeric characters (a-z and 0-9).  I have tried this many ways, but have failed to get it exactly as I want it.  First I tried Sample Code A, but that line of code fails because combination strings that contain the alphanumeric characters and a special character like the pound sign (#), will validate (Example: "hello1#").  I tried Sample Code B, but that isn't 100% what I want because if you were to add a character that isn't available on the keyboard, such as the copyright symbol or the trademak symbol.  Can someone help me, please?  Thank you.
    Sample Code A:
    interface:edit_field {
                                value = bind { key = 'new_table', object = properties },
                                fill_horizontal = 1,
                                immediate = true,
                                validate = function (interface, value)
                                  if string.find(value, "[a-z%d]")  then
                                    return true, value, "good"
                                else
                                        return false, value, "failed"
                                    end
                                end
    Sample Code B:
    interface:edit_field {
                                value = bind { key = 'new_table', object = properties },
                                fill_horizontal = 1,
                                immediate = true,
                                validate = function (interface, value)
                                    if string.find(value, "[~!@#$%^&*()_+`-={}|\%[%]:\";'<>?,./]")  then
                                    return false, value, "failed"
                                else
                                        return true, value, "good"
                                    end
                                end

    wallanceM wrote:
    Hi,
    I have an edit field in which I want to be validated immediately upon change.  I ONLY want to accept alphanumeric characters (a-z and 0-9).
    Sample Code A:
    interface:edit_field {
                                value = bind { key = 'new_table', object = properties },
                                fill_horizontal = 1,
                                immediate = true,
                                validate = function (interface, value)
                                  if string.find(value, "[a-z%d]")  then
                                    return true, value, "good"
    Hi,
    Sample Code A seems the best approach to use.  Trying to detect unwanted characters would be error prone.
    I noticed you are mixing character classes and ranges in your string.find pattern.  Have you tried using the following patterns instead?
                                  if string.find(value, "[a-z0-9]")  then
    or
                                  if string.find(value, "[%l%d]")  then
    Matt

  • Plsql - store function - passing a NULL or empty string argument

    Please see the question I posed below. Does anyone have experience with passing a NULL or empty string to a store function? THANKS.
    Hi All,
    I have a function that takes in two string arrays, status_array, and gender_array. You can see the partial code below. Somehow if the value for the string array is null, the code doesn't execute properly. It should return all employees, but instead it returns nothing. Any thoughts? THANKS.
    for iii in 1 .. status_array.count loop
    v_a_list := v_a_list || '''' || status_array(iii) || ''',';
    end loop;
    v_a_list := substr(v_a_list, 1, length(trim(v_a_list)) - 1);
    for iii in 1 .. gender_array.count loop
    v_b_list := v_b_list || '''' || gender_array(iii) || ''',';
    end loop;
    v_b_list := substr(v_b_list, 1, length(trim(v_b_list)) - 1);
    IF v_a_list IS NOT NULL and v_b_list IS NOT NULL THEN
    v_sql_stmt := 'select distinct full_name from t_employee where status in (' || v_a_list || ') and gender in (' || v_b_list || ')';
    ELSIF v_a_list IS NOT NULL and v_b_list IS NULL THEN
    v_sql_stmt := 'select distinct full_name from t_employee where status in (' || v_a_list || ') ';
    ELSIF v_a_list IS NULL and v_b_list is not null THEN
    v_sql_stmt := 'select distinct full_name from t_employee where gender in (' || v_b_list || ')';
    ELSE
    v_sql_stmt := 'select distinct full_name from t_employee';
    END IF;
    OPEN v_fullname_list FOR v_sql_stmt;
    RETURN v_fullname_list;

    Not sure what version of Oracle you are using, so here's an approach that will work with many releases.
    Create a custom SQL type, so we can use an array in SQL statements (we'll do that at the end).
    create or replace type string_list is table of varchar2(100);
    /declare your A and B lists as the type we've just created
    v_a_list    string_list default string_list();
    v_b_list    string_list default string_list();populate the nested tables with non-null values
    for iii in 1 .. status_array.count
    loop
       if status_array(iii) is not null
       then
          v_a_list.extend;
          v_a_list(v_a_list.count) := status_array(iii);
       end if;
    end loop;Here you'd want to do the same for B list.
    Then finally, return the result. Using ONE single SQL statement will help a lot if this routine is called frequently, the way you had it before would require excessive parsing, which is quite expensive in an OLTP environment. Not to mention the possibility of SQL injection. Please, please, please do some reading about BIND variables and SQL injection, they are very key concepts to understand and make use of, here's an article on the topic.
    [http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1922946900346978163]
    So here we ask for the distinct list of full names where either the status and the gender qualify based on the input data, OR the array passed in had no data to restrict the query on (the array.count = 0 does this).
    OPEN v_fullname_list FOR
       select
          distinct
             full_name
       from t_employee
       where
          status in (select /*+ CARDINALITY ( A 5 ) */ column_value from table(v_a_list) A )
          or v_a_list.count = 0
       and
          gender in (select /*+ CARDINALITY ( B 5 ) */ column_value from table(v_b_list) B )
          or v_b_list.count = 0
       );Hope that helps.
    Forgot to mention the CARDINALITY hint i added in. Oracle will have no idea how many rows these arrays (which we will treat as tables) will have, so this hint tells Oracle that you expect X (5 in this case) rows. Adjust it as you need, or remove it. If you are passing in thousands of possible values, where i've assumed you will pass in only a few, you may want to reconsider using the array approach and go for a global temporary table.
    Edited by: Tubby on Dec 11, 2009 11:45 AM
    Edited by: Tubby on Dec 11, 2009 11:48 AM
    Added link about using Bind Variables.

Maybe you are looking for

  • How do I update the software on my Airport Express?

    Hello everyone, I have an Airport Extreme base station acting as WDS and an Airport Express station. I recently upgraded the security on the Airport Extreme base station from 128-WEP to WPA (Personal), but I don't know whether I have to do something

  • IMac 20" vs 17"

    HI im currently thinking of buying an imac but i need to know if there is any major graphics performance hit in choosing the 20" model over the 17"? both have the same 2.0ghz G5 and same graphics card? but its just the fact that you have to power the

  • Help in doing sum fields from tables

    HALLOW i have a table and i wont to add the tables line to one line , to do sum if date appear more then one time like in example. i give example date---- hours 01.01.2002 6.5 01.01.2002 2.5 02.01.2002 5 03.01.2002 3 03.01.2002 3 04.01.2002 4 06.01.2

  • Importing photos from iPhoto 6 to iPhoto11.

    My beloved Quicksilver Desktop died and am buying new iMac. Any problems encountered with transferring photos stored in iPhoto 6. to iPhoto 11.

  • HT4059 Why can't I book mark my book on my ipad I used to be able to.

    I have always been able to book mark a book on my i pad from the books I download from my kindle app. Now I just started reading a book and I can't book mark it. Does anyone know why this would happen. This is the very first time.