How can I extract a number in a string before a certain character
Show older comments
I'm stuck on this problem. Imagine you have the following string: "Var.[100-200, 4000-5000]"
I want to find where the '-' and keep the number right before it. So for example, I want to keep 100 and 4000. I can't use something like: find '-' and extract 3 characters before, primarily because the number may be more than 3 characters (10 or 1000 or 100000, etc etc). Any advice would be helpful
Answers (1)
the cyclist
on 13 Jun 2023
Edited: the cyclist
on 13 Jun 2023
str = "Var.[100-200, 4000-5000]";
regexp(str,"\d*(?=-)","match")
Matching regular expressions can be a bit inscrutable at first. Here is exactly how this is working:
- The \d* indicates to look for any length of numerical digits 0-9
- The (?=-) is a "lookahead" expression for the hyphen, which means 'only find the stated pattern if it appears just before a hyphen'
- The use of the "match" input argument indicates that you want the output to be the matching string, not just the index of the matching string
You can read all the gory details in the documentation for regexp. But, be forewarned, there is a deluge of information there.
1 Comment
Stephen23
on 13 Jun 2023
You might want to avoid empty matches:
"\d+(?=-)"
% ^
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!