Page 1 of 1

How to set non empty variable inside matchtext

Posted: Fri Oct 16, 2015 9:20 am
by samjith
Hi gurus,

I have a variable exp which contains regular expression (may or may not contains number of parathesis)
so i take the count of parathesis from some code. if one parathesis found then P1, two parathesis found then P2, three parathesis found then P3, so on

How can i use P!,P2,P3 inside mathchtext
I put P!,P2,P3 into variable p, but its not working, p taken as one variable.

Code: Select all

function myregex test
   repeat with i =  1 to the number of lines in field "Main Field"
      put parathesis(names) into p --I put P!,P2,P3 into variable p
      if matchText(field "Main Field",exp, p) then 
         answer p
         return p
      else
         return "Not found"
      end if 
   end repeat
end myregex
Thanks,
Samjith

Re: How to set non empty variable inside matchtext

Posted: Fri Oct 16, 2015 12:46 pm
by Thierry
Hi samjith,

Rephrasing your query:
You have a set of regular expression which can have 0 to let say 3 captured groups.
How to use the matchText() function in this context?

Here is a simple piece of code, which I hope is simple enough to
understand the idea.

Code: Select all

 TestThierry "orange banana apple cheese bibeleskaes"

on TestThierry T
   local theResult
   put  "b.*?\b" into Rex[1]   -- no captured group
   put  "(b.*?\b)" into Rex[2] -- 1 captured group
   put  "(b.*?)\s+(a.*?)\s" into Rex[3] -- 2 captured group
   put  "(b.*?)\s+(a.*?)\s+(c.*?)\s" into Rex[4] -- 3 captured group
   put  "cat"  into Rex[5] -- no catch here
   
   repeat for each key K in Rex -- try each regex one by one
      if matchText( T, Rex[ K], p1, p2, p3) then
         if p1 is empty then  -- no captured group at all. 
            put format( "match: '%s' but no captured group\n", Rex[ K]) after theResult
            --  p2 and p3 will be empty.
         else if p2 is empty then
            put format( "match: '%s' p1: %s\n", Rex[ K], p1) after theResult
            -- p3 will be empty.
         else if p3 is empty then
            put format( "match: '%s' p1: %s  p2: %s\n", Rex[ K], p1, p2) after theResult
         else
            put format( "match: '%s' p1: %s  p2: %s  p2: %s\n", Rex[ K], p1, p2, p3) after theResult
         end if
      else
         put format( "didn't match:  '%s'\n" , Rex[ K]) after theResult
      end if
   end repeat
   put theResult into fld "fResult"
end TestThierry
and you get:

Code: Select all

didn't match:  'cat'
match: 'b.*?\b' but no captured group
match: '(b.*?\b)' p1: banana
match: '(b.*?)\s+(a.*?)\s' p1: banana  p2: apple
match: '(b.*?)\s+(a.*?)\s+(c.*?)\s' p1: banana  p2: apple  p3: cheese
Kind regards,

Thierry

Re: How to set non empty variable inside matchtext

Posted: Mon Oct 19, 2015 5:24 am
by samjith
Hi Thierry,

I think you know what i want :lol: . you are génie




Thanks
Samjith