1

I need a help with Lua and regular expression to solve the following problem. I got many strings in the following format:

"|keynameN=value"

It may contain several spaces between the vertical bar (|) and the "keyname". Also, it may contain several spaces between the keyname and the equal symbol (=).

  1. "|house10=true"
  2. "|car11 = house"
  3. "| name = car"
  4. "| wow15 = cat"

I need to use string.gsub() function passing a regexp that dynamically replaces only the name of each key (house10, car11, name, wow15) with my owns, preserving its suffix numbers, and without changing the format of the strings (e.g. preserving the spaces). I've already tried many combinations but no success.

2 Answers 2

2

I'd say

new_string = string.gsub(old_string, "^(| *)[A-Za-z]+", "%1prefix", 1)

where the prefix in "%1prefix" is the thing with which you want to replace the first part of the key. The , 1 at the end is not strictly necessary because ^ anchors the pattern at the beginning of the line, but it will potentially allow gsub to do less work.

The basic trick is to capture the | and following spaces from the input string and use them (with %1) in the replacement.

Depending on the precise forms the keys are allowed to take, the [A-Za-z] set of allowed characters may need adjustment (such as [A-Za-z_] if keys can contain underscores). The crowbar method would be to use [^0-9 =] (i.e., anything but numbers, spaces and =), but I'm not sure I'd recommend it.

Note, by the way, that Lua patterns are not regular expressions (and somewhat less powerful).

Sign up to request clarification or add additional context in comments.

Comments

0

One possible solution (see function 'my' in example below):

t = {
    {"|house10=true"          , 'residence'},
    {"|car11 = house"         , 'auto'},
    {"| name    = car"        , 'label'},
    {"|     wow15  =   cat"   , 'owo'},
}

function my(s,myown)
  s = s:gsub('(|%s*)(%a+)(%d*%s*=%s*%a+)','%1'..myown..'%3')
  return s
end

for _,v in ipairs(t) do
  print(my(v[1],v[2]))
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.