如何去除字符? [英] How do I remove the characters?

查看:22
本文介绍了如何去除字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何删除字符串中的特殊字符和字母?

How do I remove special characters and alphabets in a string ?

 qwert1234*90)!  ' this might be my cell value

我必须把它转换成

 123490  ' I mean I have to remove everything but keep only the numbers in string

但它应该允许空格!

 qwe123 4567*. 90  ' String with spaces
 123 4567 90     ' output should be

我找到了 替换 - 但是为每个字符编写一个替换会使我的代码变大.好吧,让我清楚地告诉你,不要对你隐瞒任何事情:

I found the vba Replace - but writing a replace for each character makes my code big. Well let me tell you clearly without hiding anything from you:

  1. 输入:qwe123 4567*.90 ' 带有空格的字符串 cell(1,"A").value
  2. 接下来我的想法是:123 4567 90 ' 删除字符首先保留空格
  3. A1:A3
  1. input: qwe123 4567*. 90 ' String with spaces cells(1,"A").value
  2. My idea to do these next: 123 4567 90 ' remove characters first keeping white spaces
  3. final output in A1:A3

123
4567
90

(对于每个空间,它应该插入行并填充)

你能告诉我如何删除字符串中除数字和空格之外的所有字符吗?

Could you tell me how do remove all characters except numbers and spaces in string?

提前致谢

推荐答案

您需要使用正则表达式.

You need to use a regular expression.

看这个例子:

Option Explicit

Sub Test()
    Const strTest As String = "qwerty123 456 uiops"
    MsgBox RE6(strTest)
End Sub

Function RE6(strData As String) As String
    Dim RE As Object, REMatches As Object

    Set RE = CreateObject("vbscript.regexp")
    With RE
        .MultiLine = False
        .Global = True
        .IgnoreCase = True
        .Pattern = "([0-9]| )+"   
    End With

    Set REMatches = RE.Execute(strData)
    RE6 = REMatches(0)

End Function

解释:
Pattern = "([0-9]| )+" 将匹配任何 0 个或多个包含数字 ([0-9]) 或 (|) 一个空格 ().

Explanation:
Pattern = "([0-9]| )+" will match any 0 or more group (+) containing a number ([0-9]) or (|) a space ().

关于正则表达式的更多信息:

这篇关于如何去除字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆