Extract variables from a string according to a template
- Posted by jmduro Sep 07, 2022
- 901 views
Hello, I wrote a library named extract_vars.e to extract variables from a string according to a template, with multiple levels of options. It is available here: http://jean-marc.duro.pagesperso-orange.fr/extract_vars.zip with a test program.
It is called this way:
sequence vars = extract_vars(code, template)
It returns a list of variables with some details:
- KEY : variable name in the template
- LEVEL: option level in the template (0=not optional)
- VALUE: variable value in the string
- PMIN : variable starting position in the string
- PMAX : variable ending position in the string
Here are some examples of usage:
template: http://<url>[:<port>]/search?q=<query> code : http://www.google.com/search?q=euphoria vars = [1] {"<url>", 0, "www.google.com", 7, 22} [2] {"<query>", 0, "euphoria", 31, 39'''} code : http://www.google.com:80/search?q=euphoria vars = [1] {"<url>", 0, "www.google.com", 7, 22} [2] {"<port>", 1, "80", 22, 25} [3] {"<query>", 0, "euphoria", 34'"', 42'*'} -------------------------------------------------------------------------------- template: class <name>([<parent>]) code : class TWin32() vars = [1] {"<name>", 0, "TWin32", 5, 13} code : class TWindow(TWin32) vars = [1] {"<name>", 0, "TWindow", 5, 14} [2] {"<parent>", 1, "TWin32", 14, 21} -------------------------------------------------------------------------------- template: [<prefix> ]function <name>(<a>[, <b>[[=<c>], <d>[=<e>]]]) code : function test(sequence list) vars = [1] {"<name>", 0, "test", 8, 14} [2] {"<a>", 0, "sequence list", 14, 28} code : function test(sequence list, sequence key, sequence value=0) vars = [1] {"<name>", 0, "test", 8, 14} [2] {"<a>", 0, "sequence list", 14, 28} [3] {"<b>", 1, "sequence key", 28, 42'*'} [4] {"<d>", 2, "sequence value", 42'*', 58':'} [5] {"<e>", 3, "0", 58':', 60'<'} code : function test(sequence list, sequence key="default") vars = [1] {"<name>", 0, "test", 8, 14} [2] {"<a>", 0, "sequence list", 14, 28} [3] {"<b>", 1, "sequence key", 28, 42'*'} [4] {"<c>", 3, "\"default\"", 42'*', 52'4'} code : function test(sequence list, sequence key="default", sequence value=0) vars = [1] {"<name>", 0, "test", 8, 14} [2] {"<a>", 0, "sequence list", 14, 28} [3] {"<b>", 1, "sequence key", 28, 42'*'} [4] {"<c>", 3, "\"default\"", 42'*', 52'4'} [5] {"<d>", 2, "sequence value", 52'4', 68'D'} [6] {"<e>", 3, "0", 68'D', 70'F'} code : export function test(sequence list, sequence key="default", sequence value=0) vars = [1] {"<prefix>", 1, "export", 1, 8} [2] {"<name>", 0, "test", 15, 21} [3] {"<a>", 0, "sequence list", 21, 35'#'} [4] {"<b>", 1, "sequence key", 35'#', 49'1'} [5] {"<c>", 3, "\"default\"", 49'1', 59';'} [6] {"<d>", 2, "sequence value", 59';', 75'K'} [7] {"<e>", 3, "0", 75'K', 77'M'}
Jean-Marc