Find and convert negative number strings

22 次查看(过去 30 天)
I need to find a negative number between terms A and B in a string. The following code find the 1x5 char '-20', but not as number -20. So I can not use it directly to for continue calculation. What is the easiest way to handle this?
cell2mat(regexp(SDstring,'(?<=Reference Level\d*).*?(?= dBm)','match'));
  8 个评论
Guillaume
Guillaume 2018-3-23
There are two problems:
  • cell2mat which is never going to convert a string of numbers into an actual number. Stephen's answer of using str2double for that is correct
  • the correct regular expression to detect the number. To design the correct regular expression we need to know exactly what is allowed and what isn't. Is the number always an integer or can it be decimal. Is exponential notation (e.g 1.2e5) a possibility? Is the decimal separator always '.'? Can the number include thousands separator ,? etc.
Ivy Chen
Ivy Chen 2018-3-23
Thanks and here are the specifics. The desired number is always between the 2 terms "Reference Level" AND "dBm" and
  1. It will have space(s) after/before the terms
  2. The number can be decimal
  3. No exponential notation
  4. The decimal separator is always '.'
  5. No thousands separator

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2018-3-23
编辑:Stephen23 2018-3-23
>> str = 'Reference Level -50 fieldB';
>> num = str2double(regexp(str,'[+-]?\d+','match'))
num = -50
  6 个评论
Guillaume
Guillaume 2018-3-23
If the number can be decimal, then
fmt = '(?<=Reference Level\s*)[+-]?\d*\.?\d+(?=\s*fieldB)'
Ivy Chen
Ivy Chen 2018-3-23
Got it. I only change the \s* to \W* to catch additional non-word items between two terms. thanks!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by