Filter löschen
Filter löschen

how can I extract special contents of a text?

1 Ansicht (letzte 30 Tage)
ali
ali am 11 Apr. 2016
Kommentiert: ali am 11 Apr. 2016
given a text with several parenthesis in format of (a,b). how can I extract contents of these parenthesis( a and b)? I used textscan and regexp but unsuccessful.
  2 Kommentare
Walter Roberson
Walter Roberson am 11 Apr. 2016
Are the parenthesis "nested", such as
(a,(b,c))
? Nested parenthesis are a nuisance to deal with.
ali
ali am 11 Apr. 2016
@Walter No, it's not nested. Guillaume's answer worked. Thanks.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Guillaume
Guillaume am 11 Apr. 2016
regexp(yourstring, '(?<=\()[^)]+', 'match')
should do it. It matches any sequence of anything but closing brackets preceded by an opening bracket. Note that the opening bracket has to be escaped as it's a special character in regexes.
  3 Kommentare
Guillaume
Guillaume am 11 Apr. 2016
  • (?<= starts a look-behind. It tells the regular expression engine to look for something before the match
  • \(| is the something in the look-behind. It is basically an opening bracket. Because opening brackets have special meaning in regular expression, it has to be escaped with |\.
  • ) closes the look-behind, so the whole-look behind expression is (?<=\(), which tells the regular expression that a match must be immediately preceded by an opening bracket.
  • [^)]+ means match one or more and as many (the +) of anything that is not (the ^) a closing bracket (the )).
Therefore, the regular expression matches anything preceded by an opening bracket up to a closing bracket (or the end of the string).
If the (or the end of the string) bothers you, you could make sure that the anything is actually followed by a closing bracket by adding a look-ahead expression:
regexp(yourstring, '(?<=\()[^)]+(?=\))', 'match')
As per Walter's comment, this won't work when you have nested parenthesis. But regular expression are not really suited for arbitrary nesting. You would have to write a proper parser in that case.
ali
ali am 11 Apr. 2016
ok, thank you.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by