Capture patterns

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Capture patterns

Jeff Wise

I’m trying to understand the PiL, 2nd Edition, page 184 where it talks about capture patterns when the string to be captured is quoted. My objective is to capture this string minus the quotes. I used the sample patterns provided and received errors. I altered the first pattern, and was able to get it to work. I understand the second pattern is superior, but I can not get it to function. I do not have a Unix or regex background, so your patience is appreciated. This is WinXP based Lua.

 

The sample code is attached and listed below.

 

--

-- test code based on PiL, page 184

--

 

  local abc = "name " .. '"' .. "abc123" .. '"' .. " more data"

 

 

  --local xyz = string.match(abc, '[\"'].-[\"']')

 

  local cap = '[\"' .. "']"

 

  cap = cap .. "(.-)" .. cap

 

  local cap2 = '([\"'

  cap2 = cap2 .. "'])"

  cap2 = cap2 .. "(.-)%1"

 

 

  local xyz = string.match(abc, cap)

 

  local klm = string.match(abc, "([\"'])(.-)%1")

 

  local rst = string.match(abc, '([\"])(.-)([\"])')

 

  local pqr = string.match(abc, cap2)

 

  print(abc, "**Verify String is correct**")

 

  print(klm, "First")

  print(rst, "Second")

  print(xyz, "Third")

  print(pqr, "Fourth")

 

-- Test case 3 gets desired results

-- Lua is 5.1.2

 

I could not get the commented-out code to compile. Any ideas on what I’m doing wrong?

Attachment: tstcap01.lua
Description: Binary data

Reply | Threaded
Open this post in threaded view
|

Re: Capture patterns

Duncan Cross

On Fri, Nov 14, 2008 at 7:35 PM, Jeff Wise <[hidden email]> wrote:
  --local xyz = string.match(abc, '[\"'].-[\"']')

I could not get the commented-out code to compile. Any ideas on what I'm doing wrong?

The string quote character is a single-quote, but you're backslash-escaping the double-quotes.
Reply | Threaded
Open this post in threaded view
|

Re: Capture patterns

Andreas Krinke
In reply to this post by Jeff Wise
Change

	local xyz = string.match(abc, '[\"'].-[\"']')

to

	local xyz = string.match(abc, "[\"'].-[\"']")