简体   繁体   中英

How to extract a number from a string?

abc = Sheets("02").Range("calc02").Value  // value is: Rabat 5%
xR = Mid(abc, 7, 1) // Result is: 5

This is ok, but what if the content is: Rabat 50%, or Rabat 100%
I want to extract this number only, whether it is one, two or three-digit.

使用正则表达式:

var number = Regex.Match(abc, "[0-9]+");

What about:

xR = Mid(abc, 7, Len(abc)-7)

Assuming the string is always the same, this takes the length of the string into consideration to dynamically return the value. This will only work with that format, but that sounds like what you want :)

If you instead wanted the percentage AND the word(s) in front were if variable length, this may work:

percent = Right(abc, InStr(StrReverse(abc)," ")-1)
xR = Mid(percent, 1, Len(percent)-1)
xR = Mid$(abc, 7)  ' Returns 5% or 50% etc
xR = Left$(xr, Len(xR)) - 1)  ' strips the %

or, if you want xR returned as a number

xR = Val(Mid$(abc, 7))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM