Regular expression forward slash clarification

7 views (last 30 days)
In looking over the regular expression page (<http://www.mathworks.com/help/matlab/ref/regexp.html)>, in the section describing the modes for quantifiers, the '/' symbol is introduced in a regexp, but not discussed at all. Could someone tell me what its purpose is in the expression '</?t.*>'? What I understand so far is "one '<'; whatever the slash is, repeated 0 or 1 times; one 't'; any number of characters; one '>'".

Accepted Answer

Cedric
Cedric on 21 Jun 2014
Edited: Cedric on 21 Jun 2014
The slash is a basic literal. They wanted to work with roughly the same example for the three cases, and they built a pattern whose beginning matches both opening tags '<t' and closing tags '</t'. They coded this as '</?t'. It has no real purpose in the first, greedy case. The purpose appears in the second case, where you see that it allows extracting both opening and closing tags whose name start with t.
They could have explained it as follows: if you wanted to extract all tags from the following string:
str = '<tr><td><p>text</p></td>' ;
your first attempt would probably be something like
>> regexp( str, '<.*>', 'match' )
ans =
'<tr><td><p>text</p></td>'
which doesn't work, because, by default, REGEXP is greedy: it maximizes the match. One way to overcome this could be to match not any character with . but any character different from > :
>> regexp( str, '<[^>]*>', 'match' )
ans =
'<tr>' '<td>' '<p>' '</p>' '</td>'
Yet, it is not always possible to specify a single character which should not be matched, and we sometimes have to make the greedy * quantifier lazy (as little as necessary) by appending a ?:
>> regexp( str, '<.*?>', 'match' )
ans =
'<tr>' '<td>' '<p>' '</p>' '</td>'
Etc. Now the rest is extra material for making the example more specific, but it has nothing to do with greedy/lazy quantifiers.
  1 Comment
Cedric
Cedric on 21 Jun 2014
Edited: Cedric on 21 Jun 2014
Hi Ben, note that I slightly updated my answer after you read/accepted it.

Sign in to comment.

More Answers (0)

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!