How can I extract a number in a string before a certain character

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)

str = "Var.[100-200, 4000-5000]";
regexp(str,"\d*(?=-)","match")
ans = 1×2 string array
"100" "4000"
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.

Categories

Products

Release

R2021a

Asked:

on 13 Jun 2023

Commented:

on 13 Jun 2023

Community Treasure Hunt

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

Start Hunting!