简体   繁体   English

如何从字符串中提取数字?

[英]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% 可以,但是如果内容为:拉巴特50%或拉巴特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作为数字返回

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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