How to extract substring from string?

40 次查看(过去 30 天)
I have to extract string from a string for ex: p = 'robin goes to mary'
in format such that string after 'robin' and string before 'mary' is displayed i.e. ' goes to '
*without using the text in between i.e. ' goes to ', as I don't know what lies between the start and end strings in my original text *
without using extractBetween, extractAfter, extractBefore and string indices I am using Matlab2016a

回答(3 个)

Birdman
Birdman 2018-2-24
编辑:Birdman 2018-2-26
p='robin goes to mary';
regexprep(p,'robin | mary','')
  1 个评论
Image Analyst
Image Analyst 2018-2-26
Note: that trims off spaces. If you want the spaces on there, then you can do this:
middleString = regexprep(p,'robin|mary','')
Clever approach. +1 vote. (I wish I knew regexprep better!)

请先登录,再进行评论。


Image Analyst
Image Analyst 2018-2-24
Try this:
p = 'robin goes to mary'
template = 'robin';
index1 = strfind(p, template) + length(template)
index2 = strfind(p, 'mary')
middleString = p(index1:index2)
% trim off any spaces if desired
middleString = strtrim(middleString)

Stephen23
Stephen23 2018-2-24
编辑:Stephen23 2018-2-24
Simpler to use regexprep:
>> str = 'robin goes to mary';
>> regexprep(str,'(^\w+|\w+$)','')
ans =
goes to

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by