How can I get a non-determined specific part of a string?

1 view (last 30 days)
Dear all,
I have a big string containing a lot of different phrases. I need to get some phrases that I know how they begin and how they end.
e.g:
text='Hello. I'm a really big cat. { Attention: this string is a example.} Thats all';
How can I get the part between '{ Attention:' and '. }' ?
Like this:
Result='{ Attention: this string is a example.}';
I know how can I do it in a non-simple way, with loops and so, but I think that there is something with regexp that I don't know.
Thank you all

Accepted Answer

Image Analyst
Image Analyst on 16 Sep 2013
Maybe this?:
textString = 'Hello. I am a really big cat. { Attention: this string is a example.} Thats all';
leftBraceLocation = strfind(textString, '{')
rightBraceLocation = strfind(textString, '}')
textInBetween = textString(leftBraceLocation + 1: rightBraceLocation - 1)

More Answers (2)

Jan
Jan on 16 Sep 2013
It depends. What do you want as result of:
'Hello. } { Attention: { Attention: example.{} { Attention: ';
If nested key as curly braces outside the wanted pattern are impossible, you could use:
ini = strfind(textString, '{ Attention:');
fin = strfind(textString, '}');
index = zeros(1, length(textString));
index(ini + 12) = 1;
index(fin) = -1;
result = textString(cumsum(index) ~= 0);

ab
ab on 17 Sep 2013
Edited: ab on 17 Sep 2013
I need to take all the parts that have that concrete words.
e.g:
text='Hello. Attention: there is a problem: xxxx . More things. Attention: there is another problem: xxxx . For example';
result(1)='Attention: there is a problem: xxxx '; result(2)='Attention: there is another problem: xxxx ';
Thank you all again
Edit: Sorry. It was easy.
leftBraceLocation = strfind(text, 'Attention'); rightBraceLocation = strfind(text, 'xxx');
for index = 1:length(leftBraceLocation) textInBetween{index} = text(leftBraceLocation(index) + 1: rightBraceLocation(index) - 1) end

Products

Community Treasure Hunt

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

Start Hunting!