Regular expression forward slash clarification

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 '>'".

 채택된 답변

Cedric
Cedric 2014년 6월 21일
편집: Cedric 2014년 6월 21일

2 개 추천

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

Cedric
Cedric 2014년 6월 21일
편집: Cedric 2014년 6월 21일
Hi Ben, note that I slightly updated my answer after you read/accepted it.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

질문:

Ben
2014년 6월 21일

편집:

2014년 6월 21일

Community Treasure Hunt

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

Start Hunting!

Translated by