Hi Jean-Yves,
Interesting problem.
To solve the simple case, in which there are only named tokens and literal strings, you can use regexprep to reconstruct the match, but as Ashish pointed out, you will need 'split' to recreate the portions of the initial string that are not matched.
To make things simpler, you can restrict your pattern to named tokens that do not contain nested parentheses:
>> str = 'Johan and Mary'; >> rex = '(?<husband>\S+) and (?<wife>\S+)'; >> s = regexp(str,rex,'names'); >> regexprep(rex, '\(\?<(\w*)>.*?\)', '${s.($1)}') ans =
Johan and Mary
See how this fails with a pattern using nested parentheses:
>> str = 'Johan and Mary'; >> rex = '(?<husband>[a-z]([aeiou](?=[a-z])[^aeiou])*) and (?<wife>\S+)'; >> s = regexpi(str,rex,'names') s =
husband: 'Johan' wife: 'Mary'
>> regexprep(rex, '\(\?<(\w*)>.*?\)', '${s.($1)}') ans =
Johan[^aeiou])*) and Mary
To handle nested parentheses, you need to use a recursive pattern:
>> str = 'Johan and Mary'; >> rex = '(?<husband>[a-z]([aeiou](?=[a-z])[^aeiou])*) and (?<wife>\S+)'; >> s = regexpi(str,rex,'names'); >> levelN = '\(([^()]|(??@levelN))*\)'; >> regexprep(rex, '\(\?<(\w*)>([^()]|(??@levelN))*\)', '${s.($1)}') ans =
Johan and Mary
-=>J
|