How to extract substring from string?

조회 수: 40 (최근 30일)
Siddharth singh
Siddharth singh 2018년 2월 24일
댓글: Megan 2020년 2월 15일
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