Extract only text between quotes of a string

49 ビュー (過去 30 日間)
Kirk woellert
Kirk woellert 2012 年 3 月 1 日
回答済み: Pierre Harouimi 2022 年 3 月 8 日
Folks, could use an assist. New to REGEXP but persistent. Desire only the literal text between quotes for this string:
imt = "e";
[subchunk] = regexp(textline,'\".*?\"','match','ignorecase');
imt = subchunk;
When I return the argument from my readtext file function, and print using disp(imt), I get this:
'"e"'
When I only want:
e
I assume the single quotes are associated with the disp() function?

採用された回答

Walter Roberson
Walter Roberson 2012 年 3 月 1 日
編集済み: John Kelly 2015 年 2 月 26 日
subchunk = regexp(textline, '(?<=")[^"]+(?=")', 'match');
imt = subchunk{1};
You could also consider just using a basic strfind() for '"', removing everything up to the first match and everything from the second match on.
  8 件のコメント
Walter Roberson
Walter Roberson 2012 年 3 月 2 日
(?<=") is always "look behind" (from where you are), so
(?<=")[^"]+(?<=") would mean to look behind for a double-quote, match a bunch of non-double-quote stuff, and then look behind from between the last non-double quote and the next character (or end of string) to see if the previous character was a double-quote. Which it could not be because it was only non-double-quotes in that pattern.
Look-behind from where you are, look ahead from where you are, different operators.
The output from regexp() is always a cell array, even when only one thing is being returned. You can return that cell array, and that might be appropriate in some cases, but be sure you do not try to switch() on the cell array itself: switch on the _content_ of the cell array. The
imt = subchunk{1};
strips away the cell array layer, leaving imt as a plain string (which _can_ be switch()'d on.)
Kirk woellert
Kirk woellert 2012 年 3 月 2 日
Awesome. Thanks for your help.

サインインしてコメントする。

その他の回答 (1 件)

Pierre Harouimi
Pierre Harouimi 2022 年 3 月 8 日
From R2020b, you can use pattern, much easier than the complicated regexp function.
For your pb, you the extractBetween function seems the best one:
subchunk = extractBetween("'e'", "'", "'")

カテゴリ

Help Center および File ExchangeC Shared Library Integration についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by