RegExp to remove code between triangle brackets <>

조회 수: 5 (최근 30일)
Monica
Monica 2025년 8월 28일
답변: Walter Roberson 2025년 8월 28일
I want to remove text from a string contained within triangle brackets:
string1 = '<asdfasdf> text <asdf> <";>';
string2 = 'text';
I'm trying to use regexprep to remove the bracketed text, or regexp to extract non-bracketed text. Below code does not correctly identify all the bracketed strings.
string1 = '<asdfasdf> text <asdf> <";>';
exp = '^<.*>$';
ind = regexp(string1,exp);
  댓글 수: 1
Stephen23
Stephen23 2025년 8월 28일
a = '<asdfasdf> text <asdf> <";>';
x = regexp(a,'(?<=\s)\w+')
x = 12

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

채택된 답변

Les Beckham
Les Beckham 2025년 8월 28일
편집: Les Beckham 2025년 8월 28일
Try using non-greedy matching (with a question mark: ?). This works on your example (assuming you want to remove the brackets as well as the text between them):
string1 = '<asdfasdf> text <asdf> <";>';
exp = '<.*?>';
newstring = regexprep(string1, exp, '')
newstring = ' text '
See documentation here

추가 답변 (1개)

Walter Roberson
Walter Roberson 2025년 8월 28일
This question cannot be answered meaningfully unless we know the exact rules by which it is legal to have additional "<" and ">" characters within the string contained in triangle brackets.
For example,
string1 = '<asdf<sam>asdf> text <asdf> <";>';
string2 = '<asdf<asdf> text <asdf> <";>';
string3 = '<asdf>asdf> text <asdf> <";>';
string4 = '<asdf<sa<foo>m>asdf> text <asdf> <";>';
string5 = '<asdf<s<a<asdf> text <asdf> <";>';
string6 = '<asdf>s>a>asdf> text <asdf> <";>';
are all potentially valid "characters within the string contained in triangle brackets". Allowing nested <> complicates regexp parsing a lot, especially if there is no upper limit on the number of nesting levels permitted.

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by