How to extract substring from string?

39 visualizaciones (últimos 30 días)
Siddharth singh
Siddharth singh el 24 de Feb. de 2018
Comentada: Megan el 15 de Feb. de 2020
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

Respuestas (3)

Birdman
Birdman el 24 de Feb. de 2018
Editada: Birdman el 26 de Feb. de 2018
p='robin goes to mary';
regexprep(p,'robin | mary','')
  1 comentario
Image Analyst
Image Analyst el 26 de Feb. de 2018
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!)

Iniciar sesión para comentar.


Image Analyst
Image Analyst el 24 de Feb. de 2018
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 el 24 de Feb. de 2018
Editada: Stephen23 el 24 de Feb. de 2018
Simpler to use regexprep:
>> str = 'robin goes to mary';
>> regexprep(str,'(^\w+|\w+$)','')
ans =
goes to

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by