MATLAB Answers

Extracting selected parts from text - regular expressions

1 view (last 30 days)
Daniel Miller
Daniel Miller on 14 Oct 2019
Commented: Daniel Miller on 14 Oct 2019
Hello!
I can't believe how I got stuck here, I have about ten exercises to do and this is just the first one and it is supposed to be the easiest of them. I can't even figure this one out.
So, I have the following code:
myText = 'Rome 2.7 Stockholm 3.8 Oslo 0.9 Madrid 2.8 Barcelona 12.1 Paris 9.2'
mySolution = regexp(myText,,'match')
My task is to extract only the names of the cities from "myText". What do I have to write between the two commas in the expression "regexp(myText,,'match')" to achieve this? It is likely something very obvious.
I tried the following:
myText = 'Rome 2.7 Stockholm 3.8 Oslo 0.9 Madrid 2.8 Barcelona 12.1 Paris 9.2'
mySolution = regexp(myText,[a-zA-Z],'match')
but this only separates each word when I should get the whole city names.
My brain is completely stuck, so any hint on how to solve this would perhaps get me going with the logic behind rest of the tasks too. Thank you in advance!

  0 Comments

Sign in to comment.

Accepted Answer

Daniel M
Daniel M on 14 Oct 2019
This will remove a space followed by any numbers followed by a dot follow by another number.
regexprep(myText,' [0-9]*.[0-9]','')

  3 Comments

Daniel Miller
Daniel Miller on 14 Oct 2019
Hello and thank you so much for the answer! With what you suggested, I was able to get it correct by writing this:
myText = 'Rome 2.7 Stockholm 3.8 Oslo 0.9 Madrid 2.8 Barcelona 12.1 Paris 9.2'
mySolution = regexp(myText,'[A-Za-z]*[A-Za-z]','match')
Though, the problem is, I have a hard time understanding why this leaves out the numbers and dots. What does the asterix (*) mean?
Daniel M
Daniel M on 14 Oct 2019
You don't need the second [a-zA-Z]. Your expression will match any repetition (*) of any letter, so basically any word.

Sign in to comment.

More Answers (0)

Tags

Products

Community Treasure Hunt

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

Start Hunting!