How to exclude non-capturing parts in the output of regexp()

Viewed 54

I have character vectors of the following format;

example='S(1).a=''A''; S(1).b=''B''; S(1).c=''C''; S(1).d=''D''; \n'

And I want to extract the parts before every ;. (Ultimately, I want to eval() the whole text.)

So I tried

expression='(?:.*?);\s?';
result=regexp(example,expression,'match');

The matches are correct for the given example. However, they include the non-capturing parts from ';\s?' outside ().

And when I tried different Outkeys such as 'tokens' and 'names', there is no result -- probably because I didn't enter token names.

How do I only capture the parts in the group (?:.*?)?

The other thing is .. a confirmation that my expression does correctly extract parts matching the pattern of minimal length would be great. If not, please advise how to do it correctly. I am new to regexp(). Thanks.

1 Answers

You might use a negated character class, and start the match with a non whitespace character other than a semicolon, asserting a semicolon to the right.

You can omit the optional \s? from the pattern as it is optional and would alway match in the assertion.

[^\s;][^;]*(?=;)

Regex demo

Or use a capture group () to get what you want, and matching the trailing semicolon:

([^\s;][^;]*);

Regec demo

Related